<?php

/**
 *   OPENSHOP 订单管理
 *
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 * 
 *   @package     OpenShop
 *   @version     $Id: order.php,v 1.0 $
 *   @author      baison <bs>
 */

define('IN_OS', true);
error_reporting(0);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . '/includes/modules/taobao.api/cls_api.php'); 

/* 是否启用承诺发货天数、配货功能 */
$smarty->assign('use_promise_delivery', $_CFG['use_promise_delivery']);
$smarty->assign('use_ors', $_CFG['use_ors']);

/* 获得当前管理员可操作的权限列表 */
$action_name_list = get_action_name_list();
$action_code = array();
$action_name = array();
if ($action_name_list != 'all') {
	foreach ($action_name_list as $item) {
		$action_code[] = $item['action_code'];
		$action_name[] = $item['action_name'];
	}
} else {
	$action_code[] = 'all';
}

/* 判断是否管理员 */
if ($_SESSION['action_list'] == 'all') {
	$smarty->assign('is_admin','1');
}

/*------------------------------------------------------ */
//-- 订单查询
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'order_query')
{
	/* 检查权限 */
	admin_priv('order_query');

	/* 载入配送方式 */
	$smarty->assign('shipping_list', shipping_list());

	/* 载入支付方式 */
	$smarty->assign('pay_list', payment_list());

	/* 载入国家 */
	$smarty->assign('country_list', get_regions());

	/* 载入配送站 */
	$sql = 'select s.id,s.station_name from '.$os->table('delivery_station').' as s order by s.id asc';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list',$station_list);

	/* 载入订单状态、付款状态、发货状态 */
	$smarty->assign('os_list', get_status_list('order'));
	$smarty->assign('ps_list', get_status_list('payment'));
	$smarty->assign('ss_list', get_status_list('shipping'));

	/* 模板赋值 */
	$smarty->assign('ur_here', '订单查询');
	$smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => '订单列表'));
	
	/* 显示模板 */
	assign_query_info(); 
	$smarty->display('order_query.tpl');
}

/*------------------------------------------------------ */
//-- 更新物流单号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'update_invoice_no')
{
	 $invoice_no = $_REQUEST['invoice_no'];  
	 $order_id = $_REQUEST['order_id'];  
	 $db->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET invoice_no='" . $invoice_no . "' WHERE order_id='" . $order_id . "'");
	 echo($invoice_no . '更新成功!  <a href="#" onclick="history.go(-1)">返回</a>' . $order_id);   
}

/*------------------------------------------------------ */
//-- 调用淘宝接口（发货）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'delivery_send')
{
   	if($order_sn = $_REQUEST['order_sn']) taobaoSendOrder($order_sn);
}

/*------------------------------------------------------ */
//-- 订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'list')
{
	/* 检查权限 */
	admin_priv('order_view');

	/* 更新订单，承诺发货天数、计划发货时间 */
	if ($_CFG['use_promise_delivery']) { auto_update_shipping_days(); }
	/* 自动解挂订单 */
	auto_remove_lock();
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '订单列表');

	$smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => '订单查询'));
	$smarty->assign('action_link2', array('href' => 'order2.php?act=order_ship', 'text' => '扫描出库'));
	$smarty->assign('action_link3', array('href' => 'order.php?act=order_storage', 'text' => '添加入库单'));

	$_LANG['cs'][-1] = '请选择...';
	$smarty->assign('status_list', $_LANG['cs']);   // 订单状态

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);
	
	if($action_name_list == 'all') {
		$smarty->assign('invoice_print',1);
	} elseif(in_array('order_invoice_print',$action_code)) {
		$smarty->assign('invoice_print',1);
	}
	$order_list = order_list();
 
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$smarty->assign('sort_delivery_time', '<img src="images/sort_asc.gif">');
	
	/* 载入配送方式 */
	$smarty->assign('shipping_list', shipping_list());
	
	// 增加对配送站搜索的功能
	$sql = 'select s.id,s.station_name from '.$os->table('delivery_station').' as s order by s.id asc';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list',$station_list);
	
	// 结束添加
	if(in_array('order_invoice_print',$action_code)){
		$smarty->assign('b_invoice_print',  1);
	}
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_list.tpl');
}

/*------------------------------------------------------ */
//-- 仓库待处理订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'shipping_list')
{
	/* 检查权限 */
	admin_priv('shipping_list');

	$arr = array();
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '仓管待处理订单');

	$smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => '订单查询'));
	$smarty->assign('action_link2', array('href' => 'order2.php?act=order_ship', 'text' => '扫描出库'));
	$smarty->assign('action_link3', array('href' => 'order.php?act=order_storage', 'text' => '添加入库单'));

	$smarty->assign('status_list', $_LANG['cs']);   // 订单状态

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);
	
	$arr['process_status'] = 0;
	$smarty->assign('filter',       $arr);
	
	if ($action_name_list == 'all') {
		$smarty->assign('invoice_print', 1);
	} elseif (in_array('order_invoice_print', $action_code)) {
		$smarty->assign('invoice_print', 1);
	}

	$sql = 'SELECT * FROM ' . $GLOBALS['os']->table('shipping') . ' AS s ORDER BY s.shipping_id ASC';
	$shipping_list_info = $db->getAll($sql);
	
	$type = 'shipping_list';
	$order_list = order_list($type);
	
	$sql = 'SELECT pay_id FROM ' . $GLOBALS['os']->table('payment') . " WHERE is_cod = 1 ";
	$is_cod = $GLOBALS['db']->getOne($sql);

	$smarty->assign('is_cod',   $is_cod);
	$smarty->assign('shipping_list_info',   $shipping_list_info);
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');

	// 增加对配送站搜索的功能
	$sql = 'SELECT s.id,s.station_name FROM ' . $GLOBALS['os']->table('delivery_station') . ' AS s ORDER BY s.id ASC';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list', $station_list);

	if (in_array('order_invoice_print',$action_code)) {
		$smarty->assign('b_invoice_print',  1);
	}

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_shipping_list.tpl');
}

/*------------------------------------------------------ */
//-- 财务待处理订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'cw_order_list')
{
	/* 检查权限 */
	admin_priv('cw_order_list');

	/* 模板赋值 */
	$smarty->assign('ur_here', '财务待处理订单');

	$cw_status = $_REQUEST['cw_status'];
	$smarty->assign('full_page',        1);

	$sql = 'SELECT pay_id FROM ' . $GLOBALS['os']->table('payment') . " WHERE is_cod = 1 ";
	$is_cod = $GLOBALS['db']->getOne($sql);
	$smarty->assign('is_cod',   $is_cod);

	$sql = 'SELECT * FROM ' . $os->table('shipping') . ' AS s ORDER BY s.shipping_id ASC';
	$shipping_list_info = $db->getAll($sql);
	$smarty->assign('shipping_list_info',   $shipping_list_info);

	$sql = 'SELECT * FROM ' . $os->table('payment') . ' AS p ORDER BY p.pay_id ASC';
	$pay_list_info = $db->getAll($sql);	
	$smarty->assign('pay_list_info',   $pay_list_info);
	
	$type = 'cw_order_list';
	$arr = array();
	
	$arr['cw_status'] 	  = $cw_status == NULL ? '' : $cw_status;
	$arr['order_sn']  	  = trim($_POST['order_sn']);
	$arr['ship_sn']   	  = trim($_POST['ship_sn']);
	$arr['pay_info']  	  = intval($_POST['pay_info']);
	$arr['shipping_info'] = intval($_POST['shipping_info']);
	$arr['start_time']    = trim($_POST['start_time']);
	$arr['end_time']  	  = trim($_POST['end_time']);
	
	$order_list = order_list($type, $arr);

	$smarty->assign('shipping_list_info',   $shipping_list_info);
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('cw_order_list.tpl');
}

/*------------------------------------------------------ */
//-- 挂起原因列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'suspend_reason_list')
{
    $smarty->assign('ur_here',      '挂起原因列表');
    $smarty->assign('action_link',  array('text' => '添加挂起原因', 'href' => 'order.php?act=add_suspend_reason'));
    $smarty->assign('full_page',    1);

    /* 查询记录 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('suspend_reason') . " ORDER BY reason_id ASC";
    $reason_list = $GLOBALS['db']->getAll($sql);
    $smarty->assign('reason_list',  $reason_list);

    assign_query_info();
    $smarty->display('suspend_reason_list.tpl');
}

/*------------------------------------------------------ */
//-- 添加挂起原因
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_suspend_reason')
{
    $smarty->assign('ur_here',     '添加挂起原因');
    $smarty->assign('form_action', 'insert_suspend_reason');
    $smarty->assign('action_link',  array('text' => '挂起原因列表', 'href' => 'order.php?act=suspend_reason_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('suspend_reason_info.tpl');
}

/*------------------------------------------------------ */
//-- 编辑挂起原因
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_suspend_reason')
{
    $smarty->assign('ur_here',      '编辑挂起原因');
    $smarty->assign('form_action',  'update_suspend_reason');
    $smarty->assign('action_link',  array('text' => '挂起原因列表', 'href' => 'order.php?act=suspend_reason_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('suspend_reason_info.tpl');
}

/*------------------------------------------------------ */
//-- 插入挂起原因
/*------------------------------------------------------ */

elseif ($_POST['act'] == 'insert_suspend_reason')
{
	/* 查询记录 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('suspend_reason') . " ORDER BY reason_id ASC";
    $reason_list = $GLOBALS['db']->getAll($sql);
    
    $is_only = $exc->is_only('season_name', $_POST['season_name']);
    if (!$is_only) {
        sys_msg(sprintf('名称 %s 已经存在！', stripslashes($_POST['season_name'])), 1);
    }

    $is_only = $exc->is_only('season_code', $_POST['season_code']);
    if (!$is_only) {
        sys_msg(sprintf('代码 %s 已经存在！', stripslashes($_POST['season_code'])), 1);
    }
    
    /*插入数据*/
    $sql = "INSERT INTO ".$os->table('season')."(season_name, season_code) ".
           "VALUES ('$_POST[season_name]', '$_POST[season_code]')";
    $db->query($sql);

    admin_log($_POST['season_name'], 'add', 'season');

    /* 清除缓存 */
    clear_cache_files();

    $link[0]['text'] = '继续添加挂起原因';
    $link[0]['href'] = 'season.php?act=add';
    $link[1]['text'] = '返回挂起原因列表';
    $link[1]['href'] = 'season.php?act=list';

    sys_msg('新挂起原因添加成功！', 0, $link);
}

/*------------------------------------------------------ */
//-- 编辑挂起原因
/*------------------------------------------------------ */

elseif ($_POST['act'] == 'update_suspend_reason')
{
    $smarty->assign('ur_here',      '编辑挂起原因');
    $smarty->assign('form_action',  'update_suspend_reason');
    $smarty->assign('action_link',  array('text' => '挂起原因列表', 'href' => 'order.php?act=suspend_reason_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('suspend_reason_info.tpl');
}

/*------------------------------------------------------ */
//-- 客服待处理订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'kf_order_list')
{
	/* 检查权限 */
	admin_priv('kf_order_list');

	/* 模板赋值 */
	$smarty->assign('ur_here', '客服待处理订单');

	$smarty->assign('status_list', $_LANG['cs']);   // 订单状态
	$smarty->assign('full_page',        1);
	
	$type = 'kf_order_list';
	$order_list = order_list($type);
	foreach($order_list['orders'] as $key => $val) {
		$order_list['orders'][$key]['short_to_buyer'] = sub_str($val['to_buyer'], 28);
	}
	
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('kf_order_list.tpl');
}

/*------------------------------------------------------ */
//-- 退货原因列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'return_reason_list')
{
    $smarty->assign('ur_here',      '退货原因列表');
    $smarty->assign('action_link',  array('text' => '添加退货原因', 'href' => 'order.php?act=add_return_reason'));
    $smarty->assign('full_page',    1);

    /* 查询记录 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='1' ORDER BY id ASC";
    $reason_list = $GLOBALS['db']->getAll($sql);
    $smarty->assign('reason_list',  $reason_list);

    assign_query_info();
    $smarty->display('return_reason_list.tpl');
}

/*------------------------------------------------------ */
//-- 添加退货原因页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_return_reason')
{
    $smarty->assign('ur_here',     '添加退货原因');
    $smarty->assign('form_action', 'insert_return_reason');
    $smarty->assign('action_link',  array('text' => '退货原因列表', 'href' => 'order.php?act=return_reason_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('return_reason_info.tpl');
}

/*------------------------------------------------------ */
//-- 编辑退货原因
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_return_reason')
{
    $id = intval($_POST['id']);
    $name = json_str_iconv(trim($_POST['val']));

    /* 检查是否重复 */
    if ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='{$name}' AND id<>'{$id}'")) {
        make_json_error('您输入的退货原因已存在，请换一个');
    }

    if ($GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('return_set') . " SET name='{$name}' WHERE id='{$id}'")) {
        clear_cache_files();
        make_json_result(stripslashes($name));
    }
}

/*------------------------------------------------------ */
//-- 插入退货原因
/*------------------------------------------------------ */

elseif ($_POST['act'] == 'insert_return_reason')
{
	if (trim($_POST['name']) == '') {
		sys_msg('退货原因为空！');
	} elseif ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='" . trim($_POST['name']) . "' AND type='1'")) {
		sys_msg(sprintf('退货原因 %s 已经存在！', stripslashes($_POST['name'])), 1);
	} else {
		$GLOBALS['db']->query("INSERT INTO " . $GLOBALS['os']->table('return_set') . " SET name='" . trim($_POST['name']) . "', type='1'");
		/* 清除缓存 */
    	clear_cache_files();
    	
    	$link[0]['text'] = '继续添加退货原因';
    	$link[0]['href'] = 'order.php?act=add_return_reason';
    	$link[1]['text'] = '返回退货原因列表';
    	$link[1]['href'] = 'order.php?act=return_reason_list';

    	sys_msg('新退货原因添加成功！', 0, $link);
	}
}

/*------------------------------------------------------ */
//-- 待发货订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'shipping_search')
{
	/* 检查权限 */
	admin_priv('shipping_list');

	/* 模板赋值 */
	$smarty->assign('ur_here', '待发货订单列表');

	$smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => '订单查询'));
	$smarty->assign('action_link2', array('href' => 'order2.php?act=order_ship', 'text' => '扫描出库'));

	$smarty->assign('status_list', $_LANG['cs']);   // 订单状态

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);

	$search_flag   = intval($_GET['search']);
	
	$arr = array();
	if ($search_flag == 1) {
		$arr['search_flag']    = 1;
		$arr['order_sn']  	   = trim($_POST['order_sn']);
		$arr['consignee'] 	   = trim($_POST['consignee']);
		$arr['status']    	   = trim($_POST['status']);
		$arr['process_status'] = 0;
	} else if($search_flag == 2) {
		$arr['search_flag']    = 2;
		$arr['shipping_info']  = intval($_POST['shipping_info']);
		$arr['time_start']     = trim($_POST['start_time']);
		$arr['time_end']       = trim($_POST['end_time']);
		$arr['process_status'] = 0;
		
		$arr['ck_jianhuo'] 	   = empty($_POST['ck_jianhuo'])?'0':'1';
		$arr['ck_order'] 	   = empty($_POST['ck_order'])?'0':'1';
		$arr['ck_shipping']    = empty($_POST['ck_shipping'])?'0':'1';
		
		$smarty->assign('shipping_info_id', intval($_POST['shipping_info']));
		$smarty->assign('time_start', trim($_POST['start_time']));
		$smarty->assign('time_end', trim($_POST['end_time']));
		$smarty->assign('ck_jianhuo', $_POST['ck_jianhuo']);
		$smarty->assign('filter', $arr);
	}
	
	if ($action_name_list == 'all') {
		$smarty->assign('invoice_print', 1);
	} elseif (in_array('order_invoice_print',$action_code)) {
		$smarty->assign('invoice_print', 1);
	}

	$sql = 'SELECT * FROM ' . $os->table('shipping') . ' AS s ORDER BY s.shipping_id ASC';
	$shipping_list_info = $db->getAll($sql);
	
	$type = 'shipping_list';
	$order_list = order_list($type, $arr);

	$smarty->assign('shipping_list_info',   $shipping_list_info);
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);

	// 增加对配送站搜索的功能
	$sql = 'SELECT s.id, s.station_name FROM ' . $os->table('delivery_station') . ' AS s ORDER BY s.id ASC';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list', $station_list);

	if(in_array('order_invoice_print', $action_code)) {
		$smarty->assign('b_invoice_print',  1);
	}

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_shipping_list.tpl');
}

/*------------------------------------------------------ */
//-- 退款方式列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'refund_mode_list')
{
    $smarty->assign('ur_here',      '退款方式列表');
    $smarty->assign('action_link',  array('text' => '添加退款方式', 'href' => 'order.php?act=add_refund_mode'));
    $smarty->assign('full_page',    1);

    /* 查询记录 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='0' ORDER BY id ASC";
    $mode_list = $GLOBALS['db']->getAll($sql);
    $smarty->assign('mode_list',  $mode_list);

    assign_query_info();
    $smarty->display('refund_mode_list.tpl');
}

/*------------------------------------------------------ */
//-- 添加退款方式页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_refund_mode')
{
    $smarty->assign('ur_here',     '添加退款方式');
    $smarty->assign('form_action', 'insert_refund_mode');
    $smarty->assign('action_link',  array('text' => '退款方式列表', 'href' => 'order.php?act=refund_mode_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('refund_mode_info.tpl');
}

/*------------------------------------------------------ */
//-- 编辑退款方式
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_refund_mode')
{
    $id = intval($_POST['id']);
    $name = json_str_iconv(trim($_POST['val']));

    /* 检查是否重复 */
    if ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='{$name}' AND id<>'{$id}'")) {
        make_json_error('您输入的退款方式已存在，请换一个');
    }

    if ($GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('return_set') . " SET name='{$name}' WHERE id='{$id}'")) {
        clear_cache_files();
        make_json_result(stripslashes($name));
    }
}

/*------------------------------------------------------ */
//-- 插入退款方式
/*------------------------------------------------------ */

elseif ($_POST['act'] == 'insert_refund_mode')
{
	if (trim($_POST['name']) == '') {
		sys_msg('退款方式为空！');
	} elseif ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='" . trim($_POST['name']) . "' AND type='0'")) {
		sys_msg(sprintf('退款方式 %s 已经存在！', stripslashes($_POST['name'])), 1);
	} else {
		$GLOBALS['db']->query("INSERT INTO " . $GLOBALS['os']->table('return_set') . " SET name='" . trim($_POST['name']) . "', type='0'");
		/* 清除缓存 */
    	clear_cache_files();
    	
    	$link[0]['text'] = '继续添加退款方式';
    	$link[0]['href'] = 'order.php?act=add_refund_mode';
    	$link[1]['text'] = '返回退款方式列表';
    	$link[1]['href'] = 'order.php?act=refund_mode_list';

    	sys_msg('新退款方式添加成功！', 0, $link);
	}
}

/*------------------------------------------------------ */
//-- 添加入库单页面（拒收入库、自由入库）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_storage')
{
	/* 检查权限 */
	admin_priv('order_storage');

	/* 模板赋值 */
	$smarty->assign('ur_here', '添加入库单');
	$smarty->assign('action_link', array('href' => 'order.php?act=shipping_list', 'text' => '仓管待处理订单'));
	$smarty->assign('full_page',        1);

	//$smarty->assign('storage_list', array('1' => array('code'=>'refuse','name'=>'拒收入库'), '2' => array('code'=>'free','name'=>'自由入库')));
	$smarty->assign('storage_list', array('1' => array('code'=>'refuse','name'=>'拒收入库')));
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_storage.tpl');
}

/*------------------------------------------------------ */
//-- 问题单原因列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'question_reason_list')
{
    $smarty->assign('ur_here',      '问题单原因列表');
    $smarty->assign('action_link',  array('text' => '添加问题单原因', 'href' => 'order.php?act=add_question_reason'));
    $smarty->assign('full_page',    1);

    /* 查询记录 */
    $sql = "SELECT * FROM " . $GLOBALS['os']->table('return_set') . " WHERE type='3' ORDER BY id ASC";
    $reason_list = $GLOBALS['db']->getAll($sql);
    $smarty->assign('reason_list',  $reason_list);

    assign_query_info();
    $smarty->display('question_reason_list.tpl');
}

/*------------------------------------------------------ */
//-- 添加问题单原因页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_question_reason')
{
    $smarty->assign('ur_here',     '添加问题单原因');
    $smarty->assign('form_action', 'insert_question_reason');
    $smarty->assign('action_link',  array('text' => '问题单原因列表', 'href' => 'order.php?act=question_reason_list'));
    $smarty->assign('full_page',    1);

    assign_query_info();
    $smarty->display('question_reason_info.tpl');
}

/*------------------------------------------------------ */
//-- 编辑问题单原因
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_question_reason')
{
    $id = intval($_POST['id']);
    $name = json_str_iconv(trim($_POST['val']));

    /* 检查是否重复 */
    if ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='{$name}' AND id<>'{$id}'")) {
        make_json_error('您输入的问题单原因已存在，请换一个');
    }

    if ($GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('return_set') . " SET name='{$name}' WHERE id='{$id}'")) {
        clear_cache_files();
        make_json_result(stripslashes($name));
    }
}

/*------------------------------------------------------ */
//-- 插入问题单原因
/*------------------------------------------------------ */

elseif ($_POST['act'] == 'insert_question_reason')
{
	if (trim($_POST['name']) == '') {
		sys_msg('问题单原因为空！');
	} elseif ($GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('return_set') . " WHERE name='" . trim($_POST['name']) . "' AND type='3'")) {
		sys_msg(sprintf('问题单原因 %s 已经存在！', stripslashes($_POST['name'])), 1);
	} else {
		$GLOBALS['db']->query("INSERT INTO " . $GLOBALS['os']->table('return_set') . " SET name='" . trim($_POST['name']) . "', type='3'");
		/* 清除缓存 */
    	clear_cache_files();
    	
    	$link[0]['text'] = '继续添加问题单原因';
    	$link[0]['href'] = 'order.php?act=add_question_reason';
    	$link[1]['text'] = '返回问题单原因列表';
    	$link[1]['href'] = 'order.php?act=question_reason_list';

    	sys_msg('新问题单原因添加成功！', 0, $link);
	}
}

/*------------------------------------------------------ */
//-- 订单回滚操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_rollback')
{
	/* 检查权限 */
	admin_priv('order_rollback');
	
	$order_id = $_REQUEST['order_id'];
	$order = order_info($order_id);
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '订单回滚操作');
	$smarty->assign('action_link',  array('href' => 'order.php?act=info&order_id='.$order_id, 'text' => '返回原订单'));
	$smarty->assign('status_list',  $_LANG['cs']);   // 订单状态
	$smarty->assign('full_page',    1);
	$smarty->assign('order',        $order);
	$smarty->assign('storage_list', array('1' => array('code'=>'refuse', 'name'=>'拒收入库')));
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_rollback.tpl');
}

/*------------------------------------------------------ */
//-- 拒收入库处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'refuse_storage')
{
	$ship_sn = trim($_REQUEST['ship_sn']);
	$goods_barcode = trim($_REQUEST['goods_barcode']);
	$sql = "SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE invoice_no='" . $ship_sn . "'";
	$order_sn = $GLOBALS['db']->getOne($sql);
	
	$sql = "SELECT return_type FROM " . $GLOBALS['os']->table('order_return') . " WHERE relating_order_sn='" . $order_sn . "' AND return_type='2' ";
	$return_type = $GLOBALS['db']->getOne($sql);
	$order = order_info(0, $order_sn);
	
	if(empty($order))
	{
		sys_msg('你输入的物流单号没有关联订单');		
	}
	
	if($order['pay_id'] != 2)
	{
		sys_msg('你输入的物流单号不是货到付款方式');
	}
	
	if(!$order['shipping_status'])
	{
		sys_msg('你输入的物流单号尚未发货');
	}
	
	if($return_type)
	{
		sys_msg('你输入的物流单号已经入库');		
	}
	
	/* 取得区域名 */
	$sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	"'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	"FROM " . $os->table('order_info') . " AS o " .
	"LEFT JOIN " . $os->table('region') . " AS c ON o.country = c.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS p ON o.province = p.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS t ON o.city = t.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS d ON o.district = d.region_id " .
	"WHERE o.order_id = '$order[order_id]'";
	$order['region'] = $db->getOne($sql);
	
	/* 取得订单商品 */
	$goods_list = array();
	$goods_attr = array();

	$i = 0;
	$goods_scan = '';
	$msg_flag = 0;
	$error_flag = 0;
	$storage_flag = 0;
	$refuse_goods_amount = 0;

	if ($goods_barcode != '') {
		// 根据商品条码来获得当前商品的id,尺寸id以及颜色id
		$sql = "select t.SPDM as goods_sn,t.GG1DM as color_code,t.GG2DM as size_code from ".$os->table('tmdzb').
		" as t where t.SPTM = '".$goods_barcode."'";
		$goods_scan = $db->getAll($sql);
	}

	$sql = "SELECT  o.*,co.color_code,co.color_name,s.size_code,s.size_name,g.goods_number AS storage,
		o.goods_attr " .
		" FROM " . $os->table('order_goods') . " AS o ".
		" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
		" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
		" LEFT JOIN " . $GLOBALS['os']->table('color') . " as co on o.color_id = co.color_id " .
		" LEFT JOIN " . $GLOBALS['os']->table('goods_color') . " as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id" .
		//" LEFT JOIN " . $GLOBALS['os']->table('color_lib') . " as cl on gc.img_id = cl.img_id " .
		" LEFT JOIN " . $GLOBALS['os']->table('size') . " as s on o.size_id = s.size_id " .
		" WHERE o.order_id = '$order[order_id]' ";
	$res = $db->query($sql);
	
	$refuse_goods_rec_id = '';
	$refuse_goods_number = '';
	while ($row = $db->fetchRow($res))
	{
		$sql = "UPDATE " . $os->table('order_goods') . " SET goods_barcode = '' WHERE rec_id = " . $row['rec_id'] . " AND send_number<>'0' ";
		$db->query($sql);
		
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0)
		{
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename))
			{
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link']))
				{
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}

		$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

		if ($row['extension_code'] == 'package_buy')
		{
			$row['package_goods_list'] = get_package_goods($row['goods_id']);
		}

		// 商品条码、扫描数量
		if ($goods_scan != '') {
			if ($goods_scan[0]['goods_sn'] == $row['goods_sn'] && $goods_scan[0]['color_code'] == $row['color_code'] && $goods_scan[0]['size_code'] == $row['size_code']) {
				if(($row['send_number'] - 1) < 0 ) {
					$msg_flag = 1;
				} else {
					$row['goods_barcode'] = $goods_barcode;
					$row['send_number'] = $row['send_number'] - 1;
					$sql = 'UPDATE ' . $os->table('order_goods') . ' SET send_number = send_number-1,goods_barcode = ' . $goods_barcode . ' WHERE rec_id = ' . $row['rec_id'];
					$db->query($sql);					
				}
			} else {
				$i++;
			}
		}
		
		$row['scan_number'] = intval($row['goods_number'] - $row['send_number']);
		
		if($row['rec_id'])
		{
			$sql = 'SELECT send_number = 0 FROM ' . $os->table('order_goods') . ' WHERE rec_id = ' . $row['rec_id'];
			$count = $db->getOne($sql);
		}

		if($count){
			if($refuse_goods_rec_id == '')
			{
				$refuse_goods_rec_id .= $row['rec_id'];
				$refuse_goods_number .= $row['goods_number'];
			}
			else
			{
				$refuse_goods_rec_id .= ',' . $row['rec_id'];
				$refuse_goods_number .= ',' . $row['goods_number'];
			}
			$row['scan_finish'] = true;
			$storage_flag++;
			$refuse_goods_amount += intval($row['goods_number']);
		}

		$goods_list[] = $row;
	}

	if($i == sizeof($goods_list)) {
		$msg_flag = 2;
	}

	if($storage_flag == sizeof($goods_list)) {
		$msg_flag = 3;
		
		/* 插入新的拒收入库单，状态为确认 */
		$order_refuse = array();
	
		$relating_order_sn 	= $order_sn;
		$admin_user = $_SESSION['admin_name'];
	
		$order_refuse['relating_order_sn']      = $relating_order_sn;
		$order_refuse['return_reason']			= 0;
		$order_refuse['return_pay'] 			= 0;
		$order_refuse['return_consignee'] 		= $order['consignee'];
		$order_refuse['return_email'] 			= $order['email'];
		$order_refuse['return_address'] 		= $order['address'];
		$order_refuse['return_zipcode'] 		= $order['zipcode'];
		$order_refuse['return_tel'] 			= $order['tel'];
		$order_refuse['return_mobile'] 			= $order['mobile'];
		$order_refuse['action_user']  			= $admin_user;
		$order_refuse['return_goods_amount'] 	= $refuse_goods_amount;
		$order_refuse['return_sn'] 				= get_order_return_sn();
		$order_refuse['return_order_status']    = RS_CONFIRMED;
		$order_refuse['add_time']    			= gmtime();
		$order_refuse['return_type']    		= 2;
	
		do
		{
			if ($db->autoExecute($os->table('order_return'), $order_refuse, 'INSERT', '', 'SILENT'))
			{
				break;
			}
			else
			{
				if ($db->errno() != 1062)
				{
					die($db->error());
				}
			}
		}
		while (true); // 防止订单号重复
	
		$order_refuse_id = $db->insert_id();
	
		$log_already = order_return_action_judge($order_refuse_id, RS_CONFIRMED, $action_note,$admin_user);
		if($log_already) {
			os_header("Location: order.php?act=refused_order_info&order_refuse_id=".$order_refuse_id. "\n");
			exit;
		} else {
			/* 记录log */
			order_return_action($order_refuse_id, RS_CONFIRMED, $action_note,$admin_user);
		}		
	
		// 插入拒收商品
		$refuse_goods_rec_id_list = explode(',', $refuse_goods_rec_id);
		$refuse_goods_number_list = explode(',', $refuse_goods_number);
	
		foreach ($refuse_goods_rec_id_list AS $key=>$value) {
			$goods_refuse_number = $refuse_goods_number_list[$key];
			$sql = 'INSERT INTO '.$GLOBALS['os']->table('order_return_goods').'(return_order_id,order_id,goods_id,goods_name,goods_sn,'
			.'goods_return_number,goods_buy_number,market_price,goods_price,color_id,size_id,is_real,extension_code,parent_id,is_gift,goods_barcode) '
			.' SELECT '.$order_refuse_id.',order_id,goods_id,goods_name,goods_sn,'.$goods_refuse_number.',goods_number,market_price,'
			.'goods_price,color_id,size_id,is_real,extension_code,parent_id,is_gift,goods_barcode FROM '
			.$GLOBALS['os']->table('order_goods').' WHERE rec_id = '.$value;
			$GLOBALS['db']->query($sql);
		}
	
		/* 操作成功 */
		$links[] = array('text' => '拒收入库单信息', 'href' => 'order.php?act=refused_order_info&order_refuse_id=' . $order_refuse_id);
		//sys_msg('操作成功' . $msg, 0, $links);
	}
	
	$smarty->assign('full_page', 1);
	
	/* 显示模板 */
	assign_query_info();

	$smarty->assign('focus',0);
	if( $ship_sn != '' && $goods_barcode == '') {
		$smarty->assign('focus', 1);
	}
	//$smarty->assign('storage_list', array('1' => array('code'=>'refuse','name'=>'拒收入库'), '2' => array('code'=>'free','name'=>'自由入库')));
	$smarty->assign('storage_list', array('1' => array('code'=>'refuse','name'=>'拒收入库')));
	
	$where = " WHERE op.log_info like '%" . $order_sn . "'";
	$where_print = $where . " AND op.print_type = 1 ";
	$where_delivery_print = $where . " AND op.print_type = 3 ";
	
	$sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['os']->table('order_printlog') . ' AS op ' . $where_print;		
	$count = $GLOBALS['db']->getOne($sql);    				
	$order_print_flag = $count > 0 ? 1 : 0;
	
	$sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['os']->table('order_printlog') . ' AS op ' . $where_delivery_print;		
	$count = $GLOBALS['db']->getOne($sql);    				
	$order_delivery_print_flag = $count > 0 ? 1 : 0;
	
	$sql = 'SELECT pay_id FROM ' . $GLOBALS['os']->table('payment') . " WHERE is_cod = 1 ";
	$is_code = $GLOBALS['db']->getOne($sql);

	if ($order['pay_id'] == $is_code) {
		$smarty->assign('is_code', 1);
	}

	$smarty->assign('order_sn', $order_sn);
	$smarty->assign('ship_sn', $ship_sn);
	$smarty->assign('msg_flag', $msg_flag);
	$smarty->assign('order', $order);
	$smarty->assign('goods_list', $goods_list);
	
	$smarty->display('order_storage.tpl');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'query')
{
	$module = trim($_REQUEST['module']);

	$page = '';
	$type = '';
	$arr  = array();	
	$list = array();
	
	if ($module == 'order_print_logs') {
		$page = 'order_print_logs.tpl';
		$list = get_order_print_logs();
		$smarty->assign('log_list',  $list['list']);
	} elseif ($module == 'order_return_list') {
		$page = 'order_return_list.tpl';
		$arr['return_sn']         = trim($_POST['return_sn']);
		$arr['return_consignee']  = trim($_POST['return_consignee']);
		$arr['status']            = intval($_POST['status']);
		$list = order_return_list('1',$arr);		
		$smarty->assign('order_return_list',   $list['orders_return']);
	} elseif ($module == 'order_refuse_list') {
		$page = 'order_refuse_list.tpl';
		$brr['refuse_sn']         = trim($_POST['refuse_sn']);
		$brr['refuse_consignee']  = trim($_POST['refuse_consignee']);
		$brr['status']            = intval($_POST['status']);
		$list = order_return_list('2','',$brr);		
		$smarty->assign('order_refuse_list', $list['orders_return']);
	} elseif ($module == 'order_suspend_list') {
		$page = 'order_suspend_list.tpl';
		$arr['relating_order_sn']   = trim($_REQUEST['relating_order_sn']);
		$arr['from_reason']  		= trim($_REQUEST['from_reason']);
		$arr['process_mode']        = isset($_REQUEST['process_mode']) ? intval($_REQUEST['process_mode']) : -1;
		$arr['process_status']      = isset($_REQUEST['process_status']) ? intval($_REQUEST['process_status']) : -1;
		$arr['start_time'] 			= trim($_REQUEST['start_time']);
		$arr['end_time']   			= trim($_REQUEST['end_time']);	
		$list = order_suspend_list($arr);
		$smarty->assign('order_suspend_list', $list['order_suspend_list']);
	} elseif ($module == 'order_out_list') { 
		$page = 'order_out_list.tpl';
		$arr['relating_order_sn']   = trim($_REQUEST['relating_order_sn']);
		$arr['process_mode']        = isset($_REQUEST['process_mode']) ? intval($_REQUEST['process_mode']) : -1;
		$arr['process_status']      = isset($_REQUEST['process_status']) ? intval($_REQUEST['process_status']) : -1;
		$list = order_out_list($arr);
		$smarty->assign('order_out_list', $list['order_out_list']);
	} elseif ($module == 'out_statistic') {
		$page = 'order_out_statistic.tpl';
		$list = out_statistic();
		$smarty->assign('out_goods',   $list['out']);
	} elseif ($module == 'out_details') {
		$page = 'order_out_details.tpl';
		$arr['goods_id'] = intval($_REQUEST['goods_id']);
		$arr['color_id'] = intval($_REQUEST['color_id']);
		$arr['size_id']  = intval($_REQUEST['size_id']);
		$list = out_details($arr);
		$smarty->assign('out_orders',   $list['out']);
	} elseif ($module == 'order_question_list') { 
		$page = 'order_question_list.tpl';
		$arr['relating_order_sn']   = trim($_REQUEST['relating_order_sn']);
		$arr['process_mode']        = isset($_REQUEST['process_mode']) ? intval($_REQUEST['process_mode']) : -1;
		$arr['process_status']      = isset($_REQUEST['process_status']) ? intval($_REQUEST['process_status']) : -1;
		$list = order_question_list($arr);
		$smarty->assign('order_question_list', $list['order_question_list']);
	} elseif ($module == 'order_list') {
		$page = 'order_list.tpl';
		$list = order_list();
		$smarty->assign('order_list',   $list['orders']);
	} else {
		if ($module == 'shipping_list') {
			$type = 'shipping_list';
			$page = 'order_shipping_list.tpl';
			$arr['ck_jianhuo'] = empty($_REQUEST['ck_jianhuo'])?'0':'1';
			$search_flag = trim($_POST['search_flag']);
			if ($search_flag == 1) {
				$arr['search_flag'] = 1;
				$arr['order_sn']  = trim($_POST['order_sn']);
				$arr['consignee'] = trim($_POST['consignee']);
			} else if($search_flag == 2) {
				$arr['search_flag'] = 2;
				$arr['shipping_info'] = intval($_POST['shipping_id']);
				$arr['time_start'] = trim($_POST['time_start']);
				$arr['time_end']   = trim($_POST['time_end']);
			}
		} elseif ($module == 'cw_order_list') {
			$type = 'cw_order_list';
			$page = 'cw_order_list.tpl';
			$arr['order_sn'] = trim($_POST['order_sn']);
			$arr['ship_sn'] = trim($_POST['ship_sn']);
			$arr['shipping_info'] = trim($_POST['shipping_id']);
			$arr['pay_id'] = trim($_POST['pay_id']);
			$arr['start_time'] = trim($_POST['start_time']);
			$arr['end_time']   = trim($_POST['end_time']);			
		} elseif ($module == 'kf_order_list') {
			$type = 'kf_order_list';
			$page = 'kf_order_list.tpl';
		} elseif ($module == 'order_merge') {
			$type = 'order_merge';
			$page = 'order_merge.tpl';
		} elseif ($module == 'torange_list') {
			$type = 'torange_list';
			$page = 'order_torange_list.tpl';
		}
		$list = order_list($type,$arr);
		$smarty->assign('order_list',  $list['orders']);	
	}
	
	assign_query_info();
	
	$smarty->assign('filter',       $list['filter']);
	$smarty->assign('record_count', $list['record_count']);
	$smarty->assign('page_count',   $list['page_count']);
	$sort_flag  = sort_flag($list['filter']);
	$smarty->assign($sort_flag['tag'], $sort_flag['img']);

	make_json_result($smarty->fetch($page), '', array('filter' => $list['filter'], 'page_count' => $list['page_count']));
}

/*------------------------------------------------------ */
//-- 订单详情页面
/*------------------------------------------------------ */
 
elseif ($_REQUEST['act'] == 'info')
{
	auto_update_shipping_delivery($_REQUEST['order_id'], $_REQUEST['order_sn']);
	
	/* 根据订单id或订单号查询订单信息 */
	if (isset($_REQUEST['order_id'])) {
		$order_id = intval($_REQUEST['order_id']);
		$order = order_info($order_id);
	} elseif (isset($_REQUEST['order_sn'])) {
		$order_sn = trim($_REQUEST['order_sn']);
		$order = order_info(0, $order_sn);
	} else {
		/* 如果参数不存在，退出 */
		die('invalid parameter');
	}

	/* 如果订单不存在，退出 */
	if (empty($order)) {
		die('order does not exist');
	}
	
	/* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
	$sql = "SELECT agency_id FROM " . $os->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
	$agency_id = $db->getOne($sql);
	if ($agency_id > 0) {
		if ($order['agency_id'] != $agency_id) {
			sys_msg('对不起,您没有执行此项操作的权限!');
		}
	}

	/* 取得上一个、下一个订单号 */
	if (!empty($_COOKIE['OSCP']['lastfilter'])) {
		$filter = unserialize(urldecode($_COOKIE['OSCP']['lastfilter']));
		if (!empty($filter['composite_status']))
		{
			$where = '';
			//综合状态
			switch ($filter['composite_status']) {
				case CS_AWAIT_PAY :
					$where .= order_query_sql('await_pay');
					break;

				case CS_AWAIT_SHIP :
					$where .= order_query_sql('await_ship');
					break;

				case CS_FINISHED :
					$where .= order_query_sql('finished');
					break;

				default:
					if ($filter['composite_status'] != -1) {
						$where .= " AND o.order_status = '$filter[composite_status]' ";
					}
			}
		}
	}
	
	$sql = "SELECT MAX(order_id) FROM " . $os->table('order_info') . " as o WHERE order_id < '$order[order_id]'";
	if ($agency_id > 0) {
		$sql .= " AND agency_id = '$agency_id'";
	}
	if (!empty($where)) {
		$sql .= $where;
	}
	$smarty->assign('prev_id', $db->getOne($sql));
	$sql = "SELECT MIN(order_id) FROM " . $os->table('order_info') . " as o WHERE order_id > '$order[order_id]'";
	if ($agency_id > 0) {
		$sql .= " AND agency_id = '$agency_id'";
	}
	if (!empty($where)) {
		$sql .= $where;
	}
	$smarty->assign('next_id', $db->getOne($sql));

	/* 取得用户名 */
	if ($order['user_id'] > 0) {
		$user = user_info($order['user_id']);
		if (!empty($user)) {
			$order['user_name'] = $user['user_name'];
		}
	}

	/* 取得所有办事处 */
	$sql = "SELECT agency_id, agency_name FROM " . $os->table('agency');
	$smarty->assign('agency_list', $db->getAll($sql));

	/* 取得区域名 */
	$sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
	"'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
	"FROM " . $os->table('order_info') . " AS o " .
	"LEFT JOIN " . $os->table('region') . " AS c ON o.country = c.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS p ON o.province = p.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS t ON o.city = t.region_id " .
	"LEFT JOIN " . $os->table('region') . " AS d ON o.district = d.region_id " .
	"WHERE o.order_id = '$order[order_id]'";
	$order['region'] = str_replace("\"", " ", $db->getOne($sql));
	$order['address'] = str_replace("\"", " ", $order['address']);

	/* 格式化金额 */
	if ($order['order_amount'] < 0) {
		$order['money_refund']          = abs($order['order_amount']);
		$order['formated_money_refund'] = price_format(abs($order['order_amount']));
	}

	/* 其他处理 */
	$order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);
	$order['pay_time']      = $order['pay_time'] > 0 ?
	local_date($_CFG['time_format'], $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
	$order['shipping_time'] = $order['shipping_time'] > 0 ?
	local_date($_CFG['time_format'], $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];
	
	/* 处理状态 */
	$process_status = ' (<font color="green">正常</font>) ';
	if (OPS_SUSPEND == $order['process_status']) {
		$process_status = ' (<font color="red">挂起</font>) ';
	}
	
	/* 配货状态 */
	if (ORS_UNCONFIRMED == $order['range_status']) {
		$range_status = ' (未配货) ';
	} elseif (ORS_CONFIRMED == $order['range_status']) {
		$range_status = ' (<font color="green">已配货</font>) ';
	} elseif (ORS_ERROR == $order['range_status']) {
		$range_status = ' (<font color="red">失败</font>) ';
	} elseif (ORS_OUT == $order['range_status']) {
		$range_status = ' (<font color="red">缺货</font>) ';
	}
	
	/* 问题单状态 */
	if (OQS_QUESTION == $order['question_status']) {
		$question_status = ' (<font color="red"><b>问题单</b></font>) ';
	}
	
	$order['status'] = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']] . $process_status;
	if ($_CFG['use_ors']) { $order['status'] .= $range_status; }
	$order['status'] .= $question_status;

	$order['invoice_no'] = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

	/* 取得订单的来源 */
	if ($order['from_ad'] == 0) {
		$order['referer'] = empty($order['referer']) ? '来自本站' : $order['referer'];
	} elseif ($order['from_ad'] == -1) {
		$order['referer'] = '商品站外JS投放' . ' ('.'来自站点：' . $order['referer'].')';
	} else {
		/* 查询广告的名称 */
		$ad_name = $db->getOne("SELECT ad_name FROM " . $os->table('ad') . " WHERE ad_id='$order[from_ad]'");
		$order['referer'] = '广告：' . $ad_name . ' ('.'来自站点：' . $order['referer'].')';
	}

	/* 此订单的发货备注(此订单的最后一条操作记录) */
	$sql = "SELECT action_note FROM " . $os->table('order_action') .
	" WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC ";
	$order['invoice_note'] = $db->getOne($sql);

	/* 取得订单商品总重量 */
	$weight_price = order_weight_price($order['order_id']);
	$order['total_weight'] = $weight_price['formated_weight'];
	/* 参数赋值：订单 */
	$smarty->assign('order', $order);

	/* 取得用户信息 */
	if ($order['user_id'] > 0) {
		/* 用户等级 */
		if ($user['user_rank'] > 0) {
			$where = " WHERE rank_id = '$user[user_rank]' ";
		} else {
			$where = " WHERE min_points <= " . intval($user['rank_points']) . " ORDER BY min_points DESC ";
		}
		$sql = "SELECT rank_name FROM " . $os->table('user_rank') . $where;
		$user['rank_name'] = $db->getOne($sql);

		// 用户红包数量
		$day    = getdate();
		$today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
		$sql = "SELECT COUNT(*) " .
		"FROM " . $os->table('bonus_type') . " AS bt, " . $os->table('user_bonus') . " AS ub " .
		"WHERE bt.type_id = ub.bonus_type_id " .
		"AND ub.user_id = '$order[user_id]' " .
		"AND ub.order_id = 0 " .
		"AND bt.use_start_date <= '$today' " .
		"AND bt.use_end_date >= '$today'";
		$user['bonus_count'] = $db->getOne($sql);
		$smarty->assign('user', $user);

		// 地址信息
		$sql = "SELECT * FROM " . $os->table('user_address') . " WHERE user_id = '$order[user_id]'";
		$smarty->assign('address_list', $db->getAll($sql));
	}

	/* 得到等待退货 或 已退货ID集合 */
	$return_order_ids = $db->getCol("SELECT id FROM " . $os->table('order_return') . " WHERE relating_order_sn='" . $order['order_sn'] . "' AND return_order_status<>'" . RS_FINISHED . "' AND return_order_status<>'" . RS_INVALID . "'");
	if(is_array($return_order_ids)) {
		if(implode(',', $return_order_ids) != '') { $return_order_ids_str = " AND return_order_id IN (" . implode(',', $return_order_ids) . ")"; }
	}
	$returned_order_ids = $db->getCol("SELECT id FROM " . $os->table('order_return') . " WHERE relating_order_sn='" . $order['order_sn'] . "' AND return_order_status='" . RS_FINISHED . "'");
	if(is_array($returned_order_ids)) {
		if(implode(',', $returned_order_ids) != '') { $returned_order_ids_str = " AND return_order_id IN (" . implode(',', $returned_order_ids) . ")"; }
	}
	
	/* 取得订单商品 */
	$goods_list = array();
	$goods_attr = array();
	$sql = "SELECT cl.img_file,cl.img_name,cl.img_code, o.*, co.color_id,co.color_code,co.color_name,co.color_note ,s.size_name,g.goods_number AS storage,
		o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
		" FROM " . $os->table('order_goods') . " AS o ".
		" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
		" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
		" LEFT join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id " .
		" left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id" .
		" left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id " .
		" left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id " .
		" WHERE o.order_id = '$order[order_id]' ";
	$res = $db->query($sql);
	while ($row = $db->fetchRow($res)) {
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0) {
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename)) {
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link'])) {
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}

		//等待退货 or 已退货
		if($return_order_ids_str) {
			$row['goods_return_number'] = $db->getOne("SELECT SUM(goods_return_number) AS goods_return_number FROM " . $os->table('order_return_goods') . " WHERE 1=1 $return_order_ids_str AND goods_id='" . $row['goods_id'] . "' AND color_id='" . $row['color_id'] . "' AND size_id='" . $row['size_id'] . "'");
		}
		if($returned_order_ids_str) {
			$row['goods_returned_number'] = $db->getOne("SELECT SUM(goods_return_number) AS goods_return_number FROM " . $os->table('order_return_goods') . " WHERE 1=1 $returned_order_ids_str AND goods_id='" . $row['goods_id'] . "' AND color_id='" . $row['color_id'] . "' AND size_id='" . $row['size_id'] . "'");
		}
		
		$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
		$row['formated_goods_price']    = price_format($row['goods_price']);

		$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

		if ($row['extension_code'] == 'package_buy') {
			$row['package_goods_list'] = get_package_goods($row['goods_id']);
		}

		$img_item = '<a href="'.$_CFG['pre_fetch_img'].$row['img_file'].'" target="_brank">
     <img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>
     </a>';

		$row['img_item'] = $img_item;
		$goods_list[] = $row;
	}

	$attr = array();
	$arr  = array();
	foreach ($goods_attr AS $index => $array_val) {
		foreach ($array_val AS $value) {
			$arr = explode(':', $value); //以 : 号将属性拆开
			$attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
		}
	}

	$smarty->assign('goods_attr', $attr);
	$smarty->assign('goods_list', $goods_list);

	/* 取得能执行的操作列表 */
	$operable_list = operable_list($order, $action_code);
	$smarty->assign('operable_list', $operable_list);

	/* 取得订单操作记录 */
	$act_list = array();
	$sql = "SELECT * FROM " . $os->table('order_action') . " WHERE order_id = '$order[order_id]' ORDER BY log_time DESC";
	$res = $db->query($sql);
	
	while ($row = $db->fetchRow($res)) {
		if ($row['order_status'] == OS_RETURNED && $order['order_amount'] == '0.00') {
			$row['order_status'] = OS_REFUSED;
		}
		$row['order_status']    = $_LANG['os'][$row['order_status']];
		$row['pay_status']      = $_LANG['ps'][$row['pay_status']];
		$row['shipping_status'] = $_LANG['ss'][$row['shipping_status']];
		$row['range_status'] 	= $_LANG['ors'][$row['range_status']];
		$row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
		$act_list[] = $row;
	}
	$smarty->assign('action_list', $act_list);

	/* 取得是否存在实体商品 */
	$smarty->assign('exist_real_goods', exist_real_goods($order['order_id']));
	
	//*****************************************************************
	if ($order['shipping_id']>0) {
		//$smarty->assign('print_time',   local_date($_CFG['time_format']));
		//发货地址所在地
		$region_array = array();
		$region_id = !empty($_CFG['shop_country']) ? $_CFG['shop_country'] . ',' : '';
		$region_id .= !empty($_CFG['shop_province']) ? $_CFG['shop_province'] . ',' : '';
		$region_id .= !empty($_CFG['shop_city']) ? $_CFG['shop_city'] . ',' : '';
		$region_id = substr($region_id, 0, -1);
		$region = $db->getAll("SELECT region_id, region_name FROM " . $os->table("region") . " WHERE region_id IN ($region_id)");
		if (!empty($region)) {
			foreach($region as $region_data) {
				$region_array[$region_data['region_id']] = $region_data['region_name'];
			}
		}
		
		$smarty->assign('is_cod',$order['pay_name']=='货到付款'?'√':'');
		$smarty->assign('shop_name',    str_replace("\""," ",$_CFG['shop_name']));
		$smarty->assign('province', $region_array[$_CFG['shop_province']]);
		$smarty->assign('city', $region_array[$_CFG['shop_city']]);
		$smarty->assign('shop_address', str_replace("\""," ",$_CFG['shop_address']));
		$smarty->assign('service_phone',$_CFG['service_phone']);
		$model_img = $db->getOne("SELECT model_img FROM " . $os->table("shipping") . " WHERE shipping_id=" . $order['shipping_id']);
		$smarty->assign('model_img',$model_img);
		$shipping_print = $db->getOne("SELECT shipping_print FROM " . $os->table("shipping") . " WHERE shipping_id=" . $order['shipping_id']);
		if (!empty($shipping_print)) {
			order_print_log($order['order_sn'],3);
		} else {
			$shipping_code = $db->getOne("SELECT shipping_code FROM " . $os->table('shipping') . " WHERE shipping_id=" . $order['shipping_id']);
			if (!empty($shipping_code)) {
				include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php');
			}
			if (!empty($_LANG['shipping_print'])) {
				$shipping_print = $_LANG['shipping_print'];
			}
		}
		$smarty->assign('shipping_print', $smarty->fetch("str:$shipping_print"));
	}
	//*******************************************************************

	/* 是否打印订单，分别赋值 */
	if (isset($_GET['print'])) {
		$smarty->assign('shop_name',    $_CFG['shop_name']);
		$smarty->assign('shop_url',     $os->url());
		$smarty->assign('shop_address', $_CFG['shop_address']);
		$smarty->assign('service_phone',$_CFG['service_phone']);
		$smarty->assign('print_time',   local_date($_CFG['time_format']));
		$smarty->assign('action_user',  $_SESSION['admin_name']);

		order_print_log($order['order_sn'], 1);

		$smarty->template_dir = '../' . DATA_DIR;
		$smarty->display('order_print.html');
	} else {
		/* 模板赋值 */
		$smarty->assign('ur_here', '订单信息');
		$smarty->assign('action_link', array('href' => 'order.php?act=list&' . list_link_postfix(), 'text' => '订单列表'));

		/* 显示模板 */
		assign_query_info();

		$b_lock   = 0;		/* 锁定 */
		$b_unlock = 0;		/* 解锁 */
		$b_confirm = 0;	/* 确认 */
		$b_unconfirm = 0;		/* 未确认 */
		$b_range = 0;		/* 配货 */
		$b_unrange = 0;		/* 未配货 */
		$b_cancel = 0;			/* 取消 */
		$b_invalid = 0;		/* 作废 */

		$b_pay = 0;				/* 支付 */
		$b_unpay = 0;			//未支付
		$b_pay_finish = 0;		//结算
	
		$b_print = 0;			
		$b_ship_print = 0;			/* 打印快递单 */
		$b_invoice_print = 0;		/* 发票打印 */
		$b_ship = 0;				/* 发货 */
		$b_unship = 0;				/* 未发货 */
		$b_chase = 0;
		$b_copy = 1;				/* 复制 */
		
		$b_split = 0;				/* 拆分 */
		$b_suspend = 0;			/* 挂起 */
		$b_rollback = 1;
		$b_remove_suspend = 0;		/* 回滚 */
		$b_out_handle = 0;				/* 缺货 */
		$b_question = 0;				/* 问题单 */
		$b_remove_question = 0;		/* 无问题单 */

		$lock_status = $order['lock_status'];			/* 锁定状态 */
		$order_status = $order['order_status'];		/* 订单状态 */
		$pay_status = $order['pay_status'];			/* 付款状态 */
		$shipping_status = $order['shipping_status'];		/* 发货状态 */
		$process_status = $order['process_status'];			/* 处理状态 */
		$question_status = $order['question_status'];		/* 问题单状态 */
		$range_status = $order['range_status'];				/* 配货状态 */

		$global_admin = $_SESSION['action_list'] == 'all'?1:0;	/* 是否管理员 */

		$b_returned = 0;			/* 退货 */	
		$b_refused = 0;			/* 拒收 */	

		/* 取得订单支付方式是否货到付款 */
		$payment = payment_info($order['pay_id']);
		$is_cod  = $payment['is_cod'] == 1;		

		if(OS_CONFIRMED == $order_status){
			$b_unconfirm = 1;
		}

		if(ORS_OUT == $range_status && SS_UNSHIPPED == $shipping_status && !$is_cod){
			$b_out_handle = 1;
		}
		
		if(PS_PAYED == $pay_status && SS_UNSHIPPED == $shipping_status && !$is_cod){
			$b_ship = 1;
		}

		if(OS_CONFIRMED == $order_status && SS_UNSHIPPED == $shipping_status && $is_cod){
			$b_ship = 1;
		}

		if(PS_PAYED == $pay_status){
			$b_unpay = 1;
		}

		if(OS_CONFIRMED == $order_status && PS_UNPAYED == $pay_status && SS_SHIPPED == $shipping_status && $is_cod){
			$b_pay = 1;
			$b_unconfirm = 1;
		}

		if(PS_UNPAYED == $pay_status && $lock_status != 0 && !$is_cod){
			$b_pay = 1;
		}

		if(OS_CONFIRMED == $order_status && $is_cod){
			$b_print = 1;
			$b_ship_print = 1;
			$b_invoice_print = 1;
		}

		if(PS_PAYED == $pay_status && !$is_cod){
			$b_print = 1;
			$b_ship_print = 1;
			$b_invoice_print = 1;
		}

		//if(PS_PAYED_FINISH == $pay_status){
		
		if ((SS_SHIPPED == $shipping_status) || (PS_PAYED_FINISH == $pay_status) || (PS_PAYED == $pay_status)) {
			$b_returned = 1;
		}
		
		if ($lock_status == 0 && PS_PAYED_FINISH != $pay_status) {
			$b_lock   = 1;
		} elseif ($lock_status == $_SESSION['admin_id']) {
			$b_unlock = 1;
			$b_confirm = 1;
			$b_cancel = 1;
			$b_invalid = 1;
		} elseif ($lock_status != $_SESSION['admin_id']) {
			$b_ship = 0;
			$b_pay  = 0;
			$b_print = 0;
			$b_ship_print = 0;
		} elseif ($lock_status == 1 && $global_admin) {
			$b_unlock   = 1;
		}

		if (PS_PAYED == $pay_status || SS_SHIPPED == $shipping_status ) {
			$b_unconfirm = 0;
			$b_lock   = 0;
		}

		if (OS_CONFIRMED == $order_status && PS_UNPAYED == $pay_status && SS_UNSHIPPED == $shipping_status && !$is_cod) {
			$b_pay = 1;
			$b_lock = 0;
		}   					
		
		if (OS_CONFIRMED == $order_status && $lock_status == 0 && $is_cod && SS_UNSHIPPED == $shipping_status) {
			$b_lock   = 0;
			$b_unconfirm = 1;
			$b_cancel = 1;
			$b_ship = 1;
			$b_invalid = 1;
		}

		if (OS_CONFIRMED == $order_status && PS_UNPAYED == $pay_status && (SS_RECEIVED == $shipping_status || SS_SHIPPED == $shipping_status)) {
			$b_pay = 1;
			$b_lock   = 0;
			$b_unconfirm = 0;
		}

		if (OS_UNCONFIRMED == $order_status && !$is_cod) {
			$b_pay = 1;
			$b_cancel = 1;
		}

		if (OS_CONFIRMED == $order_status && ORS_UNCONFIRMED == $range_status) {
			$b_range  = 1;
		}
		if (ORS_CONFIRMED == $range_status) {
			$b_range = 0;
			$b_unrange = 1;
		}
		if (ORS_UNCONFIRMED == $range_status) {
			$b_unrange = 0;
		}
		
		if (!$is_cod && PS_PAYED == $pay_status) {

			$b_pay = 0;
			$b_unpay = 1;
			$b_ship = 1;

			if (OS_CONFIRMED == $order_status) {
				$b_confirm  = 0;
				$b_unconfirm = 1;
			}
			if (OS_UNCONFIRMED == $order_status) {
				$b_confirm = 1;
				$b_unconfirm  = 0;
			}
			
			if ($lock_status == 0) {
				$b_lock   = 1;
				$b_unlock   = 0;
				$b_cancel = 0;
				$b_invalid = 0;
				$b_confirm  = 0;
				$b_unconfirm  = 0;

				if (OS_CONFIRMED == $order_status) {
					$b_lock   = 0;
					$b_cancel = 1;
					$b_invalid = 1;
					$b_unconfirm  = 1;
				}
			} elseif ($lock_status == 1) {
				$b_lock   = 0;
				$b_unlock   = 1;
				$b_cancel = 1;
				$b_invalid = 1;
			}

		}

		if (!$is_cod && PS_UNPAYED == $pay_status) {

			$b_pay = 1;
			$b_unpay = 0;
			$b_ship = 0;

			if (OS_CONFIRMED == $order_status) {
				$b_confirm  = 0;
				$b_unconfirm = 1;
			}
			if (OS_UNCONFIRMED == $order_status) {
				$b_confirm = 1;
				$b_unconfirm  = 0;
			}

			if ($lock_status == 0) {
				$b_lock   = 1;
				$b_unlock   = 0;
				$b_cancel = 0;
				$b_invalid = 0;
				$b_confirm  = 0;
				$b_unconfirm  = 0;

				if (OS_CONFIRMED == $order_status) {
					$b_lock = 0;
					$b_cancel = 1;
					$b_invalid = 1;
					$b_unconfirm  = 1;
				}
				//if (OS_UNCONFIRMED == $order_status) {
				//$b_cancel = 1;
				//$b_invalid = 1;
				//$b_confirm  = 1;
				//}

			} elseif ($lock_status == 1) {
				$b_lock   = 0;
				$b_unlock   = 1;
				$b_cancel = 1;
				$b_invalid = 1;
			}
		}

		if (OS_CONFIRMED == $order_status && PS_PAYED == $pay_status && (SS_RECEIVED == $shipping_status || SS_SHIPPED == $shipping_status)) {
			$b_pay_finish = 1;

			$b_lock   = 0;
			$b_unlock = 0;
			$b_confirm = 0;
			$b_unconfirm = 0;
			$b_range = 0;
			$b_unrange = 0;
			$b_cancel = 0;
			$b_invalid = 0;

			$b_pay = 0;
			$b_unpay = 0;

			$b_print = 0;
			$b_ship_print = 0;
			$b_invoice_print = 0;
			$b_ship = 0;
		}

		if (OS_INVALID == $order_status || OS_RETURNED == $order_status || OS_CANCELED == $order_status) {
			
			$b_lock   = 0;
			$b_unlock = 0;
			$b_confirm = 0;
			$b_unconfirm = 0;
			$b_range = 0;
			$b_unrange = 0;
			$b_cancel = 0;

			if (OS_CANCELED == $order_status) {
				$b_invalid = 1;
			} else {
				$b_invalid = 0;
			}

			$b_pay = 0;
			$b_unpay = 0;
			$b_pay_finish = 0;

			$b_print = 0;
			$b_ship_print = 0;
			$b_invoice_print = 0;
			$b_ship = 0;
			$b_unship = 0;
			$b_chase = 0;

			$b_returned = 0;
			
			if (SS_SHIPPED == $pay_status) {
				$b_returned = 1;
			}		
		}

		if ((OS_REFUSED == $order['order_status']) || (OS_RETURNED == $order['order_status'] && $order['order_amount'] == '0.00')) {
			$b_refused = 1;
		}
		
		if (OS_UNCONFIRMED == $order_status && PS_PAYED == $pay_status  && $is_cod && SS_UNSHIPPED == $shipping_status ) {
			$b_ship = 1;
			$b_ship_print = 1;
			if ($lock_status != 0) {
				$b_lock = 0;
			} else {
				$b_lock = 1;
			}
		} 
		
		if (OPS_NORMAL == $process_status && OS_SPLITED != $order_status) {
			$b_suspend = 1;
			$sql = 'select count(*) from '.$os->table('order_goods').' where order_id = '.$order['order_id'];
			$count = $db->getOne($sql);
			if($count > 1){
				$b_split = 1;
			}
		}
		
		if (OQS_NORMAL == $question_status) {
			$b_question = 1;
		}

		if (SS_SHIPPED == $shipping_status) {
			$b_unship = 1;
			$b_chase = 1;
			$b_suspend = 0;
			$b_remove_suspend = 0;
			$b_question = 0;
			$b_remove_question = 0;
		}
		
		if (OS_UNCONFIRMED == $order_status && PS_UNPAYED == $pay_status && SS_UNSHIPPED == $shipping_status ) {
			$b_rollback = 0;
		}
		/*已合并,已拆分,已结束*/
		if (OS_MERGED == $order_status || OS_SPLITED == $order_status || OS_FINISH == $order_status) {
			$b_lock   = 0;
			$b_unlock = 0;
			$b_confirm = 0;
			$b_unconfirm = 0;
			$b_range = 0;
			$b_unrange = 0;
			$b_cancel = 0;
			$b_invalid = 0;

			$b_pay = 0;
			$b_unpay = 0;
			$b_pay_finish = 0;

			$b_print = 0;
			$b_ship_print = 0;
			$b_invoice_print = 0;
			$b_ship = 0;
			$b_unship = 0;
			$b_chase = 0;
			
			$b_suspend = 0;
			$b_remove_suspend = 0;
			$b_copy = 0;
			$b_rollback = 0;
			$b_question = 0;
			
			if (OPS_SUSPEND == $process_status) {
				$b_remove_suspend = 1;
			}
		}
		
		if (OQS_QUESTION == $question_status) {
			$b_remove_question = 1;
		}
			
		if (OPS_SUSPEND == $process_status) {
			$b_ship = 0;
			$b_unship = 0;
			$b_chase = 0;
			$b_remove_suspend = 1;
		}
		
		if ($_CFG['use_ors']) {
			if (ORS_UNCONFIRMED == $range_status) {
				$b_unrange = 0;
				$b_ship = 0;
			} elseif (ORS_ERROR == $range_status || ORS_OUT == $range_status) {
				$b_range = 0;
				$b_unrange = 0;
				$b_ship = 0;
				$b_out_handle = 1;
			}
		}
		
		$smarty->assign('b_lock', $b_lock);
		$smarty->assign('b_unlock', $b_unlock);
		$smarty->assign('b_confirm', $b_confirm);
		$smarty->assign('b_unconfirm', $b_unconfirm);
		$smarty->assign('b_range', $b_range);
		$smarty->assign('b_unrange', $b_unrange);
		$smarty->assign('b_cancel', $b_cancel);
		$smarty->assign('b_invalid', $b_invalid);

		$smarty->assign('b_pay', $b_pay);
		$smarty->assign('b_unpay', $b_unpay);
		$smarty->assign('b_pay_finish', $b_pay_finish);

		$smarty->assign('b_print', $b_print);
		$smarty->assign('b_ship_print', $b_ship_print);
		$smarty->assign('b_invoice_print', $b_invoice_print);
		$smarty->assign('b_ship', $b_ship);
		$smarty->assign('b_unship', $b_unship);
		$smarty->assign('b_chase', $b_chase);

		$smarty->assign('b_copy', $b_copy);

		$smarty->assign('b_suspend', $b_suspend);
		$smarty->assign('b_rollback', $b_rollback);
		$smarty->assign('b_remove_suspend', $b_remove_suspend);
		$smarty->assign('b_question', $b_question);
		$smarty->assign('b_remove_question', $b_remove_question);
				
		$smarty->assign('b_returned', $b_returned);
		$smarty->assign('b_refused', $b_refused);
		$smarty->assign('b_split', $b_split);
		$smarty->assign('b_out_handle', $b_out_handle);

		if ((($lock_status == 0 && OS_CONFIRMED == $order_status) ||
		($lock_status > 0 && $lock_status == $_SESSION['admin_id'])) && OPS_SUSPEND != $process_status) {
			$editable = true;
		}
		if (!empty($editable)) {
			$smarty->assign('editable',$editable);
		}

		$smarty->assign('delivery_type', $order['delivery_type']);
		$delivery_station_id = $order['delivery_station_id'];
		$smarty->assign('delivery_station_id',$delivery_station_id);
		if ($delivery_station_id != 0) {
			$sql = 'select s.station_name from '.$os->table('delivery_station').' as s where s.id = '.$delivery_station_id;
			$delivery_station_info = $db->getOne($sql);
			$smarty->assign('delivery_station_info', $delivery_station_info);
		}
		
		if (!empty($user)) {
			$smarty->assign('user_copy', serialize($user));
		}
		$smarty->assign('order_copy', serialize($order));
		$smarty->assign('goods_list_copy', serialize($goods_list));
		
		// 结束查询
		$smarty->display('order_info.tpl');
	}
}

/*------------------------------------------------------ */
//-- 未知内容
/*------------------------------------------------------ */

elseif ($_REQUEST['act']=='txm') 
{
	if(!empty($_REQUEST['tx_no']))
	//EAN_13($_REQUEST['tx_no']);
	UPCAbarcode($_REQUEST['tx_no']);
	//exit();
}

/*------------------------------------------------------ */
//-- 添加/修改订单（处理提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'step_post')
{
	/* 检查权限 */
	admin_priv('order_edit');

	/* 取得参数 step */
	$step_list = array('user', 'add_user', 'edit_goods', 'add_goods', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money', 'invoice','delivery');
	$step = isset($_REQUEST['step']) && in_array($_REQUEST['step'], $step_list) ? $_REQUEST['step'] : 'user';

	/* 取得参数 order_id */
	$order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
	if ($order_id > 0) {
		$old_order = order_info($order_id);
	}

	/* 取得参数 step_act 添加还是编辑 */
	$step_act = isset($_REQUEST['step_act']) ? $_REQUEST['step_act'] : 'add';

	/* 添加新用户 */
	if ('add_user' == $step) {
		$user_name = isset($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';
		$nick_name = isset($_REQUEST['nick_name']) ? $_REQUEST['nick_name'] : '';
		if (empty($user_name)) {
			sys_msg('客户名不能为空，请核对。');
			exit;
		} elseif ($GLOBALS['db']->getOne("SELECT user_id FROM " . $GLOBALS['os']->table('users') . " WHERE user_name='{$user_name}'")) {
			sys_msg('客户名已经存在，请重新输入。');
			exit;
		} else {
			$GLOBALS['db']->query("INSERT INTO " . $GLOBALS['os']->table('users') . " SET user_name='{$user_name}', nick_name='{$nick_name}', reg_time='" . gmtime() . "'");
			$user_id = $GLOBALS['db']->insert_id();
			os_header("Location: order.php?act=step_post&step=user&order_id=0&step_act=add&user=$user_id");
			exit;
		}
	}
	
	/* 插入订单信息 */
	elseif ('user' == $step) {
		/* 取得参数：user_id */
		$user_id = ($_REQUEST['anonymous'] == 1) ? 0 : intval($_REQUEST['user']);

		/* 插入新订单，状态为无效 */
		$order = array(
			'user_id'           => $user_id,
			'add_time'          => gmtime(),
			'order_status'      => OS_INVALID,
			'shipping_status'   => SS_UNSHIPPED,
			'pay_status'        => PS_UNPAYED,
			'from_ad'           => 0,
			'referer'           => '管理员添加'
		);

		do
		{
			$order['order_sn'] = get_order_sn();
			if ($db->autoExecute($os->table('order_info'), $order, 'INSERT', '', 'SILENT')) {
				break;
			} else {
				if ($db->errno() != 1062) {
					die($db->error());
				}
			}
		}
		while (true); // 防止订单号重复

		$order_id = $db->insert_id();

		/* todo 记录日志 */
		admin_log($order['order_sn'], 'add', 'order');

		/* 插入 pay_log */
		$sql = 'INSERT INTO ' . $os->table('pay_log') . " (order_id, order_amount, order_type, is_paid)" .
		" VALUES ('$order_id', 0, '" . PAY_ORDER . "', 0)";
		$db->query($sql);

		/* 下一步 */
		os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
		exit;
	}
	
	/* 编辑商品信息 */
	elseif ('edit_goods' == $step) {
		if (isset($_POST['rec_id'])) {
			foreach ($_POST['rec_id'] AS $key => $rec_id) {
				/* 取得参数 */
				$goods_price = floatval($_POST['goods_price'][$key]);
				$goods_number = intval($_POST['goods_number'][$key]);
				$goods_original_number = intval($_POST['goods_original_number'][$key]);

				// 增加订单商品中单个商品是否'被拒收'状态位的修改
				$is_rejected = intval($_POST['is_rejected'][$key]);
				$goods_attr = $_POST['goods_attr'][$key];

				if (intval($GLOBALS['_CFG']['use_storage']) > 0) {
					$sql = 'SELECT goods_id,color_id,size_id FROM '.$GLOBALS['os']->table('order_goods').' WHERE rec_id = '.$rec_id;
					$res = $GLOBALS['db']->getRow($sql);

					$goods_id = $res['goods_id'];
					$size_id  = $res['size_id'];
					$color_id = $res['color_id'];

					$inventory_number = '';

					$sql_inventory = "SELECT i.goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " AS i WHERE i.goods_id = '$goods_id' AND i.color_id = '$color_id' AND i.size_id = '$size_id'";

					$inventory_result = $GLOBALS['db']->getRow($sql_inventory);

					if ($inventory_result) {
						$inventory_number = $inventory_result['goods_number_available'];
					} else {
						$inventory_number = 0;
					}

					if ($inventory_number < $goods_number) {
						sys_msg('非常抱歉，你添加的商品库存数量只有' . $inventory_number . '件，您最多只能输入' . $inventory_number.'件。');
						exit;
					}

					if ($_CFG['stock_dec_time'] == SDT_PLACE) {
						$number_offset = 0;
						if ($goods_number < $goods_original_number) {
							$number_offset = $goods_original_number - $goods_number;
							$sql = "UPDATE " . $GLOBALS['os']->table('goods_inventory') .
								" SET goods_number_available = goods_number_available + " . $number_offset .
								" WHERE goods_id = '$goods_id' AND color_id = '$color_id' AND size_id = '$size_id'";
							$db->query($sql);
						} elseif ($goods_original_number < $goods_number) {
							$number_offset = $goods_number - $goods_original_number;
							$sql = "UPDATE ".$GLOBALS['os']->table('goods_inventory') .
								" SET goods_number_available = goods_number_available - " . $number_offset.
								" WHERE goods_id = '$goods_id' AND color_id = '$color_id' AND size_id = '$size_id'";
							$db->query($sql);
						}
					}
				}

				/* 修改 */
				$sql = "UPDATE " . $os->table('order_goods') .
					" SET goods_price = '$goods_price', " .
					"goods_number = '$goods_number', " .
					"is_rejected = '$is_rejected' " .
					"WHERE rec_id = '$rec_id' LIMIT 1";
				$db->query($sql);
			}

			/* 更新商品总金额和订单总金额 */
			$goods_amount = order_amount($order_id);
			
			$sql = 'SELECT SUM(goods_number) FROM '.$GLOBALS['os']->table('order_goods').' AS og WHERE og.order_id = '.$order_id;
			$goods_count = $db->getOne($sql);
			
			update_order($order_id, array('goods_amount' => $goods_amount, 'goods_count' => $goods_count));
			update_order_amount($order_id);

			/* 更新 pay_log */
			update_pay_log($order_id);

			/* todo 记录日志 */
			$sn = $old_order['order_sn'];
			$new_order = order_info($order_id);
			if ($old_order['total_fee'] != $new_order['total_fee']) {
				$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
			}
			admin_log($sn, 'edit', 'order');
		}

		/* 跳回订单商品 */
		os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
		exit;
	}
	
	/* 添加商品 */
	elseif ('add_goods' == $step) {
		/* 取得参数 */
		$goods_id = intval($_POST['goodslist']);
		$goods_price = $_POST['add_price'] != 'user_input' ? floatval($_POST['add_price']) : floatval($_POST['input_price']);

		$color_id = intval($_POST['color_id']);
		$size_id  = intval($_POST['size_id']);

		$goods_attr = get_goods_spec_info(array('goods_id'=>$goods_id,'color_id'=>$color_id,'size_id'=>$size_id));
		$goods_number = $_POST['add_number'];

		/* 如果使用库存，则判断库存 */
		if ($GLOBALS['_CFG']['use_storage'] > 0) {
			$inventory_number = '';
			$goods_info = '';

			$sql_inventory = "SELECT i.goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " AS i WHERE i.goods_id = '$goods_id' AND i.color_id = '$color_id' AND i.size_id = '$size_id'";

			$inventory_result = $GLOBALS['db']->getRow($sql_inventory);

			if ($inventory_result) {
				$inventory_number = $inventory_result['goods_number_available'];
			} else {
				$inventory_number = 0;
			}

			if ($inventory_number < $goods_number) {
				sys_msg('非常抱歉，你添加的商品库存数量只有'.$inventory_number.'件，您最多只能输入'.$inventory_number.'件。');
				exit;
			}
		}

		/* 插入订单商品 */
		$sql = "INSERT INTO " . $os->table('order_goods') .
			" (order_id, goods_id, goods_name, goods_sn, " .
			"goods_number, market_price, goods_price, goods_attr, " .
			"is_real, extension_code, parent_id, is_gift,color_id,size_id)" .
			" SELECT '$order_id', goods_id, goods_name, goods_sn, " .
			"'$goods_number', market_price, '$goods_price', '" . $goods_attr . "', " .
			"is_real, extension_code, 0, 0 ,'$color_id','$size_id'" .
			"FROM " . $os->table('goods') .
			" WHERE goods_id = '$goods_id' LIMIT 1";
		$db->query($sql);

		/* 更新商品总金额和订单总金额 */
		$sql = 'SELECT SUM(goods_number) FROM '.$GLOBALS['os']->table('order_goods').' AS og WHERE og.order_id = '.$order_id;
		$goods_count = $db->getOne($sql);
		
		update_order($order_id, array('goods_amount' => order_amount($order_id),'goods_count' => $goods_count));
		update_order_amount($order_id);

		/* 更新 pay_log */
		update_pay_log($order_id);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');

		/* 跳回订单商品 */
		os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
		exit;
	}
	
	/* 商品 */
	elseif ('goods' == $step) {
		/* 下一步 */
		if (isset($_POST['next'])) {
			os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=consignee\n");
			exit;
		}
		/* 完成 */
		elseif (isset($_POST['finish'])) {
			/* 初始化提示信息和链接 */
			$msgs   = array();
			$links  = array();

			/* 如果已付款，检查金额是否变动，并执行相应操作 */
			$order = order_info($order_id);
			handle_order_money_change($order, $msgs, $links);

			/* 显示提示信息 */
			if (!empty($msgs)) {
				sys_msg(join(chr(13), $msgs), 0, $links);
			} else {
				/* 跳转到订单详情 */
				os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
				exit;
			}
		}
	}

	/* 配送 */
	elseif ('delivery' == $step) {
		$delivery_type = intval($_POST['delivery_type']);
		$delivery_station_id = intval($_POST['delivery_station_id']);

		/* 下一步 */
		if (isset($_POST['next'])) {
			os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=consignee\n");
			exit;
		}
		/* 完成 */
		elseif (isset($_POST['finish'])) {
			/* 修改 */
			$sql = "UPDATE " . $os->table('order_info') .
				" SET delivery_type = '$delivery_type', " .
				" delivery_station_id = '$delivery_station_id' " .
				" WHERE order_id = '$order_id'";
			$db->query($sql);
			/* 跳转到订单详情 */
			os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
			exit;
		}
	}

	/* 保存收货人信息 */
	elseif ('consignee' == $step) {
		/* 保存订单 */
		$order = $_POST;
		$order['agency_id'] = get_agency_by_regions(array($order['country'], $order['province'], $order['city'], $order['district']));
		update_order($order_id, $order);

		/* 该订单所属办事处是否变化 */
		$agency_changed = $old_order['agency_id'] != $order['agency_id'];

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		admin_log($sn, 'edit', 'order');

		if (isset($_POST['next'])) {
			/* 下一步 */
			if (exist_real_goods($order_id)) {
				/* 存在实体商品，去配送方式 */
				os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=shipping\n");
				exit;
			} else {
				/* 不存在实体商品，去支付方式 */
				os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
				exit;
			}
		} elseif (isset($_POST['finish'])) {
			/* 如果是编辑且存在实体商品，检查收货人地区的改变是否影响原来选的配送 */
			if ('edit' == $step_act && exist_real_goods($order_id)) {
				$order = order_info($order_id);

				/* 取得可用配送方式 */
				$region_id_list = array(
					$order['country'], $order['province'], $order['city'], $order['district']
				);
				$shipping_list = available_shipping_list($region_id_list);

				/* 判断订单的配送是否在可用配送之内 */
				$exist = false;
				foreach ($shipping_list AS $shipping) {
					if ($shipping['shipping_id'] == $order['shipping_id']) {
						$exist = true;
						break;
					}
				}

				/* 如果不在可用配送之内，提示用户去修改配送 */
				if (!$exist) {
					// 修改配送为空，配送费和保价费为0
					update_order($order_id, array('shipping_id' => 0, 'shipping_name' => ''));
					$links[] = array('text' => '选择配送方式', 'href' => 'order.php?act=edit&order_id=' . $order_id . '&step=shipping');
					sys_msg('由于您修改了收货人所在地区，导致原来的配送方式不再可用，请重新选择配送方式', 1, $links);
				}
			}

			/* 完成 */
			if ($agency_changed) {
				os_header("Location: order.php?act=list\n");
			} else {
				os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
			}
			exit;
		}
	}

	/* 发货 */
	elseif ('shipping' == $step)
	{
		/* 如果不存在实体商品，退出 */
		if (!exist_real_goods($order_id)) {
			die ('Access Denied');
		}

		/* 取得订单信息 */
		$order_info = order_info($order_id);
		$region_id_list = array($order_info['country'], $order_info['province'], $order_info['city'], $order_info['district']);

		/* 保存订单 */
		$shipping_id = $_POST['shipping'];
		$shipping = shipping_area_info($shipping_id, $region_id_list);
		$weight_amount = order_weight_price($order_id);
		$shipping_fee = shipping_fee($shipping['shipping_code'], $shipping['configure'], $weight_amount['weight'], $weight_amount['amount'], $weight_amount['number']);
		$order = array(
			'shipping_id' => $shipping_id,
			'shipping_name' => addslashes($shipping['shipping_name']),
			'shipping_fee' => $shipping_fee
		);

		if (isset($_POST['insure'])) {
			/* 计算保价费 */
			$order['insure_fee'] = shipping_insure_fee($shipping['shipping_code'], order_amount($order_id), $shipping['insure']);
		} else {
			$order['insure_fee'] = 0;
		}
		update_order($order_id, $order);
		update_order_amount($order_id);

		/* 更新 pay_log */
		update_pay_log($order_id);

		/* 清除首页缓存：发货单查询 */
		clear_cache_files('index.dwt');

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');

		if (isset($_POST['next'])) {
			/* 下一步 */
			os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
			exit;
		} elseif (isset($_POST['finish'])) {
			/* 初始化提示信息和链接 */
			$msgs   = array();
			$links  = array();

			/* 如果已付款，检查金额是否变动，并执行相应操作 */
			$order = order_info($order_id);
			
			//***************根据九牧王的特殊需求，暂时去掉和费用关联的逻辑**********************
			
//			handle_order_money_change($order, $msgs, $links);
//
//			/* 如果是编辑且配送不支持货到付款且原支付方式是货到付款 */
//			if ('edit' == $step_act && $shipping['support_cod'] == 0)
//			{
//				$payment = payment_info($order['pay_id']);
//				if ($payment['is_cod'] == 1)
//				{
//					/* 修改支付为空 */
//					update_order($order_id, array('pay_id' => 0, 'pay_name' => ''));
//					$msgs[]     = '由于您修改了配送方式，导致原来的支付方式不再可用，请重新选择配送方式';
//					$links[]    = array('text' => '选择支付方式', 'href' => 'order.php?act=' . $step_act . '&order_id=' . $order_id . '&step=payment');
//				}
//			}

			/* 显示提示信息 */
			if (!empty($msgs)) {
				sys_msg(join(chr(13), $msgs), 0, $links);
			} else {
				/* 完成 */
				os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
				exit;
			}
		}
	}
	
	/* 保存支付信息 */
	elseif ('payment' == $step) {
		/* 取得支付信息 */
		$pay_id = $_POST['payment'];
		$payment = payment_info($pay_id);

		/* 计算支付费用 */
		$order_amount = order_amount($order_id);
		if ($payment['is_cod'] == 1) {
			$order = order_info($order_id);
			$region_id_list = array(
				$order['country'], $order['province'], $order['city'], $order['district']
			);
			$shipping = shipping_area_info($order['shipping_id'], $region_id_list);
			$pay_fee = pay_fee($pay_id, $order_amount, $shipping['pay_fee']);
		} else {
			$pay_fee = pay_fee($pay_id, $order_amount);
		}

		/* 保存订单 */
		$order = array(
			'pay_id' => $pay_id,
			'pay_name' => addslashes($payment['pay_name']),
			'pay_fee' => $pay_fee,
			'prepay_time' => local_strtotime($_REQUEST['prepay_date'])
		);
		update_order($order_id, $order);
		update_order_amount($order_id);

		/* 更新 pay_log */
		update_pay_log($order_id);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');

		if (isset($_POST['next'])) {
			/* 下一步 */
			os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=other\n");
			exit;
		} elseif (isset($_POST['finish'])) {
			/* 初始化提示信息和链接 */
			$msgs   = array();
			$links  = array();

			/* 如果已付款，检查金额是否变动，并执行相应操作 */
			$order = order_info($order_id);
			handle_order_money_change($order, $msgs, $links);

			/* 显示提示信息 */
			if (!empty($msgs)) {
				sys_msg(join(chr(13), $msgs), 0, $links);
			} else {
				/* 完成 */
				os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
				exit;
			}
		}
	}
	
	/* 其它 */
	elseif ('other' == $step) {	   
		$sql = 'SELECT goods_amount FROM ' . $os->table('order_info') . ' WHERE order_id = ' . $order_id;
		$goods_amount = $db->getOne($sql);
	    $sql = 'SELECT order_sn FROM ' . $os->table('order_info') . ' WHERE order_id = ' . $order_id;
		$order_sn = $db->getOne($sql);
		
		/* 保存订单 */
		$order = array();
		if (isset($_POST['pack']) && $_POST['pack'] > 0) {
			$pack               = pack_info($_POST['pack']);
			$order['pack_id']   = $pack['pack_id'];
			$order['pack_name'] = addslashes($pack['pack_name']);
			
			$sql = 'SELECT free_money FROM ' . $os->table('pack') . ' WHERE pack_id = ' . $order['pack_id'];
			$pack_free_money = $db->getOne($sql);
			
			if ($goods_amount >= floatval($pack_free_money)) {
				$order['pack_fee']  = 0;
			} else {
				$order['pack_fee']  = $pack['pack_fee'];
			}
		} else {
			$order['pack_id']   = 0;
			$order['pack_name'] = '';
			$order['pack_fee']  = 0;
		}
		if (isset($_POST['card']) && $_POST['card'] > 0) {
			$card               = card_info($_POST['card']);
			$order['card_id']   = $card['card_id'];
			$order['card_name'] = addslashes($card['card_name']);
		
			$sql = 'SELECT free_money FROM ' . $os->table('card') . ' WHERE card_id = ' . $order['card_id'];
			$card_free_money = $db->getOne($sql);	

			if ($goods_amount >= floatval($card_free_money)) {
				$order['card_fee']  = 0;
			} else {
				$order['card_fee']  = $card['card_fee'];
			}
			
			$order['card_message'] = $_POST['card_message'];
		} else {
			$order['card_id']   = 0;
			$order['card_name'] = '';
			$order['card_fee']  = 0;
			$order['card_message'] = '';
		}
		$order['inv_type']      = $_POST['inv_type'];
		$order['inv_payee']     = $_POST['inv_payee'];
		$order['inv_content']   = $_POST['inv_content'];
		$order['how_oos']       = $_POST['how_oos'];
		$order['postscript']    = $_POST['postscript'];
		$order['to_buyer']      = $_POST['to_buyer'];
        $order['order_from']    = $_POST['order_from'];
  	    $order['to_admin']      = $_POST['to_admin'];
      	$order['process_status']  = OPS_NORMAL;
      	
		update_order($order_id, $order); 
		order_action($order_sn, 0, 0, 0, $order['to_admin']);
		
		update_order_amount($order_id);

		/* 更新 pay_log */
		update_pay_log($order_id);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		admin_log($sn, 'edit', 'order');

		if (isset($_POST['next'])) {
			/* 下一步 */
			os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=money\n");
			exit;
		} elseif (isset($_POST['finish'])) {
			/* 完成 */
			os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
			exit;
		}
	}
	
	/* 费用 */
	elseif ('money' == $step) {
		/* 取得订单信息 */
		$old_order = order_info($order_id);
		if ($old_order['user_id'] > 0) {
			/* 取得用户信息 */
			$user = user_info($old_order['user_id']);
		} 
		/* 保存信息 */
		$order['goods_amount']  = $old_order['goods_amount'];
		$order['discount']      = isset($_POST['discount']) && floatval($_POST['discount']) >= 0 ? round(floatval($_POST['discount']), 2) : 0;
		$order['tax']           = round(floatval($_POST['tax']), 2);
		$order['shipping_fee']  = isset($_POST['shipping_fee']) && floatval($_POST['shipping_fee']) >= 0 ? round(floatval($_POST['shipping_fee']), 2) : 0;
		$order['insure_fee']    = isset($_POST['insure_fee']) && floatval($_POST['insure_fee']) >= 0 ? round(floatval($_POST['insure_fee']), 2) : 0;
		$order['pay_fee']       = floatval($_POST['pay_fee']) >= 0 ? round(floatval($_POST['pay_fee']), 2) : 0;
		$order['pack_fee']      = isset($_POST['pack_fee']) && floatval($_POST['pack_fee']) >= 0 ? round(floatval($_POST['pack_fee']), 2) : 0;
		$order['card_fee']      = isset($_POST['card_fee']) && floatval($_POST['card_fee']) >= 0 ? round(floatval($_POST['card_fee']), 2) : 0;

		$order['money_paid']    = $old_order['money_paid'];
		$order['surplus']       = 0;
		$order['integral']      = 0;
		$order['integral_money']= 0;
		$order['bonus_id']      = 0;
		$order['bonus']         = 0;

		/* 计算待付款金额 */
		$order['order_amount']  = $order['goods_amount'] - $order['discount']
		+ $order['tax']
		+ $order['shipping_fee']
		+ $order['insure_fee']
		+ $order['pay_fee']
		+ $order['pack_fee']
		+ $order['card_fee']
		- $order['money_paid'];
		
		if ($order['order_amount'] > 0) {
			if ($old_order['user_id'] >= 0) {
				/* 如果选择了红包，先使用红包支付 */
				if ($_POST['bonus_id'] > 0) {
					/* todo 检查红包是否可用 */
					$order['bonus_id']      = $_POST['bonus_id'];
					$bonus_users            = bonus_info($_POST['bonus_id']);
					$order['bonus']         = $bonus_users['type_money'];
				}

				if (isset($_POST['bonus_sn']) && $_POST['bonus_sn'] != '') {
					$bonus_sn = $_POST['bonus_sn'];
					$bonus_offline          = bonus_info(0,$bonus_sn);
					$order['bonus']         = floatval(intval($order['bonus']) + intval($bonus_offline['type_money']));
				}
				
				$order['order_amount']  -= $order['bonus'];
				/* 使用红包之后待付款金额仍大于0 */
				if ($order['order_amount'] > 0) {
					/* 如果设置了积分，再使用积分支付 */
					if (isset($_POST['integral']) && intval($_POST['integral']) > 0) {
						/* 检查积分是否足够 */
						$order['integral']          = intval($_POST['integral']);
						$order['integral_money']    = value_of_integral(intval($_POST['integral']));
						if ($old_order['integral'] + $user['pay_points'] < $order['integral'])
						{
							sys_msg('客户积分不足');
						}

						$order['order_amount'] -= $order['integral_money'];
					}

					if ($order['order_amount'] > 0) {
						/* 如果设置了余额，再使用余额支付 */
						if (isset($_POST['surplus']) && floatval($_POST['surplus']) >= 0) {
							/* 检查余额是否足够 */
							$order['surplus'] = round(floatval($_POST['surplus']), 2);
							if ($old_order['surplus'] + $user['user_money'] + $user['credit_line'] < $order['surplus']) {
								sys_msg('客户余额不足');
							}

							/* 如果红包和积分和余额足以支付，把待付款金额改为0，退回部分积分余额 */
							$order['order_amount'] -= $order['surplus'];
							if ($order['order_amount'] < 0) {
								$order['surplus']       += $order['order_amount'];
								$order['order_amount']  = 0;
							}
						}
					} else {
						/* 如果红包和积分足以支付，把待付款金额改为0，退回部分积分 */
						$order['integral_money']    += $order['order_amount'];
						$order['integral']          = integral_of_value($order['integral_money']);
						$order['order_amount']      = 0;
					}
				} else {
					/* 如果红包足以支付，把待付款金额设为0 */
					$order['order_amount'] = 0;
				}
			}
		}

		update_order($order_id, $order);
		
		if ($_POST['bonus_id'] > 0){
			$sql = 'UPDATE '.$os->table('user_bonus').' SET used_time = '.gmtime().',user_id = '.$old_order['user_id'].',order_id ='.$order_id.' WHERE bonus_id = '.$_POST['bonus_id'];
			$db->query($sql);
		}
		
		if (isset($_POST['bonus_sn']) && $_POST['bonus_sn'] != '') {
			$sql = 'UPDATE '.$os->table('user_bonus').' SET used_time = '.gmtime().',user_id = '.$old_order['user_id'].',order_id ='.$order_id.'  WHERE bonus_sn = '.$_POST['bonus_sn'];
			$db->query($sql);
		}
	
		/* 更新 pay_log */
		update_pay_log($order_id);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');

		/* 如果余额、积分、红包有变化，做相应更新 */
		if ($old_order['user_id'] > 0) {
			$user_money_change = $old_order['surplus'] - $order['surplus'];
			if ($user_money_change != 0) {
				log_account_change($user['user_id'], $user_money_change, 0, 0, 0, sprintf('编辑订单 %s ，改变使用预付款支付的金额', $old_order['order_sn']));
			}

			$pay_points_change = $old_order['integral'] - $order['integral'];
			if ($pay_points_change != 0) {
				log_account_change($user['user_id'], 0, 0, 0, $pay_points_change, sprintf('编辑订单 %s ，改变使用积分支付的数量', $old_order['order_sn']));
			}

			if ($old_order['bonus_id'] != $order['bonus_id']) {
				if ($old_order['bonus_id'] > 0) {
					$sql = "UPDATE " . $os->table('user_bonus') .
						" SET used_time = 0, order_id = 0 " .
						"WHERE bonus_id = '$old_order[bonus_id]' LIMIT 1";
					$db->query($sql);
				}

				if ($order['bonus_id'] > 0) {
					$sql = "UPDATE " . $os->table('user_bonus') .
						" SET used_time = '" . gmtime() . "', order_id = '$order_id' " .
						"WHERE bonus_id = '$order[bonus_id]' LIMIT 1";
					$db->query($sql);
				}
			}
		}

		if (isset($_POST['finish'])) {
			/* 订单改为已确认，（未付款） */
			$pay_status = PS_UNPAYED;
			/* 完成 */
			if ($step_act == 'add') {
				$action_note = '后台添加';

				if ($_CFG['use_ors']) { //启用配货功能
					$arr['order_status'] = OS_UNCONFIRMED;
					$arr['range_status'] = ORS_UNCONFIRMED;
				} else { //不启用配货功能
					$arr['order_status'] = OS_CONFIRMED;
					$arr['range_status'] = ORS_CONFIRMED;
					$arr['confirm_time'] = gmtime();
				}
				$log_already = order_action_judge($old_order['order_sn'], $arr['order_status'], SS_UNSHIPPED, $pay_status, $action_note, '', $arr['range_status']);
				if ($log_already) {
					os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
					exit;
				} else {
					if ($order['order_amount'] <= 0) {
						$arr['pay_status']  = PS_PAYED;
						$arr['pay_time']    = gmtime();
						$pay_status = PS_PAYED;
					}
					
					$sql_tmp = 'SELECT goods_id FROM ' .$os->table('order_goods').' WHERE order_id = '.$order_id;
					$sql = 'SELECT sales_type FROM '.$os->table('goods').' as g where g.goods_id in ('.$sql_tmp.')';
					$st_res = $db->getAll($sql);

					$product = 1;

					foreach($st_res as $st) {
						$product = $product * $st['sales_type'];
					}

					$process_status = ($product == 1) ? OPS_NORMAL : OPS_SUSPEND;
					if(OPS_SUSPEND == $process_status) {
						/* 插入挂起订单数据部分 */
						$action_note .= '-含有联营或预售商品,系统自动挂起';
						$add_time = gmtime();
						$order_sn = $old_order['order_sn'];
						$sql = "INSERT INTO ".$os->table('order_suspend')." (relating_order_id, relating_order_sn, suspend_reason, from_user, add_time) VALUES ('$order_id', '$order_sn', '含有联营或预售商品','后台添加','$add_time')";
						$db->query($sql);
					}
					
					$arr['process_status'] = $process_status;
					update_order($order_id, $arr);
					
					/* 记录log */
					order_action($old_order['order_sn'], $arr['order_status'], SS_UNSHIPPED, $pay_status, $action_note, $_SESSION['admin_name'], $arr['range_status']);
				}

				/* 库存处理 */
				manage_good_inventory($order_id, 'order', true);
				/* 更新计划发货时间 */
				auto_update_shipping_delivery($order_id);
			}

			/* 发送邮件 */
			if ($_CFG['send_confirm_email'] == '1') {
				$tpl = get_mail_template('order_confirm');
				$smarty->assign('order', $old_order);
				$smarty->assign('shop_name', $_CFG['shop_name']);
				$smarty->assign('send_date', local_date($_CFG['date_format']));
				$smarty->assign('sent_date', local_date($_CFG['date_format']));
				$content = $smarty->fetch('str:' . $tpl['template_content']);
				if (!send_mail($old_order['consignee'], $old_order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
					$msg = '发送邮件失败';
				}
			}
			
			/* 初始化提示信息和链接 */
			$msgs   = array();
			$links  = array();

			/* 如果已付款，检查金额是否变动，并执行相应操作 */
			$order = order_info($order_id);
			handle_order_money_change($order, $msgs, $links);

			/* 显示提示信息 */
			if (!empty($msgs)) {
				sys_msg(join(chr(13), $msgs), 0, $links);
			} else {
				os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
				exit;
			}
		}
	}
	
	/* 保存发货后的配送方式和发货单号 */
	elseif ('invoice' == $step) {
		/* 如果不存在实体商品，退出 */
		if (!exist_real_goods($order_id)) {
			die ('Hacking Attemp');
		}

		/* 保存订单 */
		$shipping_id    = $_POST['shipping'];
		$shipping       = shipping_info($shipping_id);
		$invoice_no     = $_POST['invoice_no'];
		$order = array(
			'shipping_id'   => $shipping_id,
			'shipping_name' => addslashes($shipping['shipping_name']),
			'invoice_no'    => $invoice_no
		);
		update_order($order_id, $order);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		admin_log($sn, 'edit', 'order');

		if (isset($_POST['finish'])) {
			os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
			exit;
		}
	}
}

/*------------------------------------------------------ */
//-- 拷贝订单操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'info_copy')
{
	/* 检查权限 */
	//admin_priv('info_copy');
	
	$user_copy = unserialize(preg_replace("/\\\/", '', $_REQUEST['user_copy']));
	$address_list_copy = unserialize(preg_replace("/\\\/", '', $_REQUEST['address_list_copy']));
	$order_copy = unserialize(preg_replace("/\\\/", '', $_REQUEST['order_copy']));
	$goods_list_copy = unserialize(preg_replace("/\\\/", '', $_REQUEST['goods_list_copy']));
	
	//添加订单 - 第一步（选用户）
	$user_id = $order_copy['user_id'];
	$order = array(
		'user_id'           => $user_id,
		'add_time'          => gmtime(),
		'order_status'      => OS_INVALID,
		'shipping_status'   => SS_UNSHIPPED,
		'pay_status'        => PS_UNPAYED,
		'from_ad'           => 0,
		'referer'           => $order_copy['referer'],
		'extension_code'    => $order_copy['extension_code'],
		'extension_id'      => $order_copy['extension_id']
		);
	do
	{
		$order['order_sn'] = get_order_sn();
		if ($db->autoExecute($os->table('order_info'), $order, 'INSERT', '', 'SILENT')) {
			break;
		} else {
			if ($db->errno() != 1062) {
				die($db->error());
			}
		}
	}
	while (true); // 防止订单号重复
	
	$order_id = $db->insert_id();
	if ($order_id > 0) {
		$old_order = order_info($order_id);
	}
	admin_log($order['order_sn'], 'add', 'order');
	$sql = 'INSERT INTO ' . $os->table('pay_log') . " (order_id, order_amount, order_type, is_paid)" .
	" VALUES ('$order_id', 0, '" . PAY_ORDER . "', 0)";
	$db->query($sql);
	
	//添加订单 - 第二步（选商品）
	foreach($goods_list_copy as $key => $value) {
		$cur_recid = $value['rec_id'];
		$goods_id = $value['goods_id'];
		$goods_name = $value['goods_name'];
		$goods_price = $value['goods_price'];
		$color_id = $value['color_id'];
		$size_id = $value['size_id'];
		$goods_attr = get_goods_spec_info(array('goods_id'=>$goods_id, 'color_id'=>$color_id, 'size_id'=>$size_id));
		$goods_number = $value['goods_number'];
		
		if (intval($GLOBALS['_CFG']['use_storage']) > 0) {
			$inventory_number = '';
			$goods_info = '';
			$sql_inventory = "SELECT i.goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " AS i WHERE i.goods_id = '$goods_id' AND i.color_id = '$color_id' AND i.size_id = '$size_id'";
			$inventory_result = $GLOBALS['db']->getRow($sql_inventory);
			if ($inventory_result) {
				$inventory_number = $inventory_result['goods_number_available'];
			}else{
				$inventory_number = 0;
			}
			if ($inventory_number < $goods_number) {
				sys_msg('非常抱歉，你添加的商品（'.$goods_name.'）库存数量只有'.$inventory_number.'件。');
				exit;
			}
		}

		/* 插入订单商品 */
		if($goods_id > 0) { //真实商品
			$sql = "INSERT INTO " . $os->table('order_goods') .
			" (order_id, goods_id, goods_name, goods_sn, " .
			"goods_number, market_price, goods_price, transaction_price, goods_attr, " .
			"is_real, extension_code, parent_id, is_gift,color_id,size_id)" .
			" SELECT '$order_id', goods_id, goods_name, goods_sn, " .
			"'$goods_number', market_price, '$goods_price', '$transaction_price', '" . $goods_attr . "', " .
			"is_real, extension_code, 0, 0 ,'$color_id','$size_id'" .
			"FROM " . $os->table('goods') .
			" WHERE goods_id = '$goods_id' LIMIT 1";
		} else { //折扣虚拟商品
			$sql = "INSERT INTO " . $os->table('order_goods') . 
			" (order_id, goods_id, goods_name, goods_sn, " .
			"goods_number, market_price, goods_price, transaction_price, goods_attr, " .
			"is_real, extension_code, parent_id, is_gift, color_id, size_id ) " . 
			" SELECT '$order_id', goods_id, goods_name, goods_sn, " . 
			"'$goods_number', market_price, goods_price, transaction_price, goods_attr, " . 
			"is_real, extension_code, parent_id, is_gift, color_id, size_id " . 
			"FROM " . $os->table('order_goods') . " WHERE rec_id='$cur_recid' AND order_id='" . $value['order_id'] . "' AND goods_id='$goods_id' LIMIT 1";
		}
		$db->query($sql);

		$sql = 'SELECT SUM(goods_number) FROM '.$GLOBALS['os']->table('order_goods').' AS og WHERE og.order_id = '.$order_id;
		$goods_count = $db->getOne($sql);
		
		/* 更新商品总金额和订单总金额 */
		update_order($order_id, array('goods_amount' => order_amount($order_id), 'goods_count' => $goods_count));
		update_order_amount($order_id);

		/* 更新 pay_log */
		update_pay_log($order_id);

		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');
	}
	
	//添加订单 - 第三步（设置收货人）
	$consignee_array = array(
		'consignee'     => $order_copy['consignee'],
		'email'         => $order_copy['email'],
		'country'       => $order_copy['country'],
		'province'      => $order_copy['province'],
		'city'          => $order_copy['city'],
		'district'      => $order_copy['district'],
		'address'       => $order_copy['address'],
		'zipcode'       => $order_copy['zipcode'],
		'tel'           => $order_copy['tel'],
		'mobile'        => $order_copy['mobile'],
		'sign_building' => $order_copy['sign_building'],
		'best_time'     => $order_copy['best_time'],
		'agency_id'     => get_agency_by_regions(array($order_copy['country'], $order_copy['province'], $order_copy['city'], $order_copy['district']))
	);
	update_order($order_id, $consignee_array);
	
	/* 该订单所属办事处是否变化 */
	$agency_changed = $old_order['agency_id'] != $order_copy['agency_id'];
	$sn = $old_order['order_sn'];
	admin_log($sn, 'edit', 'order');
	
	//添加订单 - 第四步（设置配送方式）
	if (exist_real_goods($order_id)) {
		$region_id_list = array($order_copy['country'], $order_copy['province'], $order_copy['city'], $order_copy['district']);
		$shipping_id = $order_copy['shipping_id'];
		$shipping = shipping_area_info($shipping_id, $region_id_list);
		$weight_amount = order_weight_price($order_id);
		$shipping_fee = shipping_fee($shipping['shipping_code'], $shipping['configure'], $weight_amount['weight'], $weight_amount['amount'], $weight_amount['number']);
		$insure_fee = $order_copy['insure_fee'];
		$shipping_array = array(
			'shipping_id'   => $shipping_id,
			'shipping_name' => addslashes($shipping['shipping_name']),
			'shipping_fee'  => $shipping_fee,
			'insure_fee'    => $insure_fee
		);
		update_order($order_id, $shipping_array);
		update_order_amount($order_id);
		update_pay_log($order_id);
		
		/* todo 记录日志 */
		$sn = $old_order['order_sn'];
		$new_order = order_info($order_id);
		if ($old_order['total_fee'] != $new_order['total_fee']) {
			$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
		}
		admin_log($sn, 'edit', 'order');
	}
	
	//添加订单 - 第五步（设置支付方式）
	$payment_array = array(
		'pay_id'   => $order_copy['pay_id'],
		'pay_name' => addslashes($order_copy['pay_name']),
		'pay_fee'  => $order_copy['pay_fee']
	);
	update_order($order_id, $payment_array);
	update_order_amount($order_id);
	update_pay_log($order_id);

	/* todo 记录日志 */
	$sn = $old_order['order_sn'];
	$new_order = order_info($order_id);
	if ($old_order['total_fee'] != $new_order['total_fee']) {
		$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
	}
	admin_log($sn, 'edit', 'order');
	
	//添加订单 - 第六步（设置其它）
	$other_array = array(
		'pack_id'      => $order_copy['pack_id'],
		'pack_name'    => addslashes($order_copy['pack_name']),
		'pack_fee'     => $order_copy['pack_fee'],
		'card_id'      => $order_copy['card_id'],
		'card_name'    => $order_copy['card_name'],
		'card_fee'     => $order_copy['card_fee'],
		'card_message' => $order_copy['card_message'],
		'inv_type'     => $order_copy['inv_type'],
		'inv_payee'    => $order_copy['inv_payee'],
		'inv_content'  => $order_copy['inv_content'],
		'how_oos'      => $order_copy['how_oos'],
		'postscript'   => $order_copy['postscript'],
		'to_buyer'     => $order_copy['to_buyer'],
		'lock_status'  => 1
	);
	
	update_order($order_id, $other_array);
	update_order_amount($order_id);
	update_pay_log($order_id);
	
	/* todo 记录日志 */
	$sn = $old_order['order_sn'];
	admin_log($sn, 'edit', 'order');
	
	//添加订单 - 第七步（设置费用）
	if($order_copy['order_amount'] <= 0) {
		$order_copy['order_amount'] = $order_copy['goods_amount'] - $order_copy['discount'] + $order_copy['tax'] + $order_copy['shipping_fee'] + $order_copy['insure_fee'] + $order_copy['pay_fee'] + $order_copy['pack_fee'] + $order_copy['card_fee'];
	}
	$money_array = array(
		'goods_amount'   => $order_copy['goods_amount'],
		'discount'       => $order_copy['discount'],
		'tax'            => $order_copy['tax'],
		'shipping_fee'   => $order_copy['shipping_fee'],
		'insure_fee'     => $order_copy['insure_fee'],
		'pay_fee'        => $order_copy['pay_fee'],
		'pack_fee'       => $order_copy['pack_fee'],
		'card_fee'       => $order_copy['card_fee'],
		'order_amount'   => $order_copy['order_amount']
	);
	update_order($order_id, $money_array);
	
	/*
	if ($money_array['bonus_id'] > 0) {
		$sql = 'UPDATE '.$os->table('user_bonus').' SET used_time = '.gmtime().',user_id = '.$old_order['user_id'].',order_id ='.$order_id.' WHERE bonus_id = '.$money_array['bonus_id'];
		$db->query($sql);
	}
	if (isset($money_array['bonus_sn']) && $money_array['bonus_sn'] != '') {
		$sql = 'UPDATE '.$os->table('user_bonus').' SET used_time = '.gmtime().',user_id = '.$old_order['user_id'].',order_id ='.$order_id.' WHERE bonus_sn = '.$money_array['bonus_sn'];
		$db->query($sql);
	}
	*/
	
	/* 更新 pay_log */
	update_pay_log($order_id);

	/* todo 记录日志 */
	$sn = $old_order['order_sn'];
	$new_order = order_info($order_id);
	if ($old_order['total_fee'] != $new_order['total_fee']) {
		$sn .= ',' . sprintf('订单总金额由 %s 变为 %s', $old_order['total_fee'], $new_order['total_fee']);
	}
	admin_log($sn, 'edit', 'order');
	
	/* 如果余额、积分、红包有变化，做相应更新 */
	/*
	if ($old_order['user_id'] > 0) {
		$user_money_change = $old_order['surplus'] - $money_array['surplus'];
		if ($user_money_change != 0) {
			log_account_change($old_order['user_id'], $user_money_change, 0, 0, 0, sprintf('编辑订单 %s ，改变使用预付款支付的金额', $old_order['order_sn']));
		}

		$pay_points_change = $old_order['integral'] - $money_array['integral'];
		if ($pay_points_change != 0) {
			log_account_change($user['user_id'], 0, 0, 0, $pay_points_change, sprintf('编辑订单 %s ，改变使用积分支付的数量', $old_order['order_sn']));
		}

		if ($old_order['bonus_id'] != $money_array['bonus_id']) {
			if ($old_order['bonus_id'] > 0) {
				$sql = "UPDATE " . $os->table('user_bonus') .
				" SET used_time = 0, order_id = 0 " .
				"WHERE bonus_id = '$old_order[bonus_id]' LIMIT 1";
				$db->query($sql);
			}
			if ($money_array['bonus_id'] > 0) {
				$sql = "UPDATE " . $os->table('user_bonus') .
				" SET used_time = '" . gmtime() . "', order_id = '$order_id' " .
				"WHERE bonus_id = '$money_array[bonus_id]' LIMIT 1";
				$db->query($sql);
			}
		}
	}
	*/
	
	//添加订单 - 第八步（锁定）
	$pay_status = PS_UNPAYED;
	$action_note = '后台添加';
	$log_already = order_action_judge($old_order['order_sn'], OS_LOCK, SS_UNSHIPPED, $pay_status, $action_note);
	if ($log_already) {
		os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
		exit;
	} else {
		$arr['order_status'] = OS_UNCONFIRMED;
		update_order($order_id, $arr);
		update_order_lock_status($order_id, $_SESSION['admin_id']);
		/* 记录log */
		order_action($old_order['order_sn'], OS_LOCK, SS_UNSHIPPED, $pay_status, $action_note);
	}
	/* 如果使用库存，且下订单时减库存，则减少库存 */
	/*
	if ($_CFG['use_storage'] == '1') {
		change_goods_inventory($order_id, true);
	}
	*/
	
	/* 发送邮件 */
	if ($_CFG['send_confirm_email'] == '1') {
		$tpl = get_mail_template('order_confirm');
		$new_order = order_info($order_id);
		$smarty->assign('order', $new_order);
		$smarty->assign('shop_name', $_CFG['shop_name']);
		$smarty->assign('send_date', local_date($_CFG['date_format']));
		$smarty->assign('sent_date', local_date($_CFG['date_format']));
		$content = $smarty->fetch('str:' . $tpl['template_content']);
		if (!send_mail($new_order['consignee'], $new_order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
			$msg = '发送邮件失败';
		}
	}
	
	/* 初始化提示信息和链接 */
	$msgs   = array();
	$links  = array();

	/* 如果已付款，检查金额是否变动，并执行相应操作 */
	/*
	$new_order = order_info($order_id);
	handle_order_money_change($new_order, $msgs, $links);
	*/

	/* 显示提示信息 */
	if (!empty($msgs)) {
		sys_msg(join(chr(13), $msgs), 0, $links);
	} else {
		os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
		exit;
	}
}

/*------------------------------------------------------ */
//-- 添加/修改订单（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
	$priv_str = $_REQUEST['act'] == 'add'?'order_add':'order_edit';

	/* 检查权限 */
	admin_priv($priv_str);

	/* 取得参数 order_id */
	$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
	$smarty->assign('order_id', $order_id);

	/* 取得参数 step */
	$step_list = array('user', 'add_user', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money','delivery');
	$step = isset($_GET['step']) && in_array($_GET['step'], $step_list) ? $_GET['step'] : 'user';
	$smarty->assign('step', $step);

	/* 取得参数 act */
	$act = $_GET['act'];
	$smarty->assign('ur_here', (($act == 'add') ?
	'添加订单' : '编辑订单') .' - '. $_LANG['step'][$step]);
	$smarty->assign('step_act', $act);

	/* 取得订单信息 */
	if ($order_id > 0) {
		$order = order_info($order_id);

		/* 如果已发货，就不能修改订单了（配送方式和发货单号除外） */
		if ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED) {
			if ($step != 'shipping') {
				sys_msg('您不能修改已发货的订单');
			} else {
				$step = 'invoice';
				$smarty->assign('step', $step);
			}
		}

		$smarty->assign('order', $order);
	} else {
		if ($act != 'add' || ($step != 'user' && $step != 'add_user')) {
			die('invalid params');
		}
	}

	if ('user' == $step) {
		// 选择客户
	} elseif ('add_user' == $step) {
		// 添加新客户
	} elseif ('delivery' == $step) {
		// 取得配送站列表
		$sql = 'SELECT s.id,s.station_name FROM '.$GLOBALS['os']->table('delivery_station') . ' AS s WHERE s.in_use = 1 ORDER BY s.station_name ASC';
		$station_list = $GLOBALS['db']->getAll($sql);
		$smarty->assign('station_list', $station_list);
	} elseif ('goods' == $step) {
		/* 增删改商品 */
		$goods_list = order_goods($order_id);
		if (!empty($goods_list)) {
			foreach ($goods_list AS $key => $goods) {
				/* 计算属性数 */
				$attr = $goods['goods_attr'];
				if ($attr == '') {
					$goods_list[$key]['rows'] = 1;
				} else {
					$goods_list[$key]['rows'] = count(explode(chr(13), $attr));
				}
			}
		}

		$smarty->assign('goods_list', $goods_list);
		/* 取得商品总金额 */
		$smarty->assign('goods_amount', order_amount($order_id));
	} elseif ('consignee' == $step) {
		// 设置收货人
		$exist_real_goods = exist_real_goods($order_id);
		$smarty->assign('exist_real_goods', $exist_real_goods);

		/* 取得收货地址列表 */
		if ($order['user_id'] > 0) {
			$smarty->assign('address_list', address_list($order['user_id']));

			$address_id = isset($_REQUEST['address_id']) ? intval($_REQUEST['address_id']) : 0;
			if ($address_id > 0) {
				$address = address_info($address_id);
				if ($address) {
					$order['consignee']     = $address['consignee'];
					$order['country']       = $address['country'];
					$order['province']      = $address['province'];
					$order['city']          = $address['city'];
					$order['district']      = $address['district'];
					$order['email']         = $address['email'];
					$order['address']       = $address['address'];
					$order['zipcode']       = $address['zipcode'];
					$order['tel']           = $address['tel'];
					$order['mobile']        = $address['mobile'];
					$order['sign_building'] = $address['sign_building'];
					$order['best_time']     = $address['best_time'];
					$smarty->assign('order', $order);
				}
			}
		}

		if ($exist_real_goods) {
			/* 取得国家 */
			$smarty->assign('country_list', get_regions());
			if ($order['country'] > 0) {
				/* 取得省份 */
				$smarty->assign('province_list', get_regions(1, $order['country']));
				if ($order['province'] > 0) {
					/* 取得城市 */
					$smarty->assign('city_list', get_regions(2, $order['province']));
					if ($order['city'] > 0) {
						/* 取得区域 */
						$smarty->assign('district_list', get_regions(3, $order['city']));
					}
				}
			}
		}
	} elseif ('shipping' == $step) { 
		// 选择配送方式
		if (!exist_real_goods($order_id)) {
			die ('Hacking Attemp');
		}

		/* 取得可用的配送方式列表 */
		$region_id_list = array(
			$order['country'], $order['province'], $order['city'], $order['district']
		);
		$shipping_list = available_shipping_list($region_id_list);

		/* 取得配送费用 */
		$total = order_weight_price($order_id);
		foreach ($shipping_list AS $key => $shipping) {
			$shipping_fee = shipping_fee($shipping['shipping_code'],
			unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number']);
			$shipping_list[$key]['shipping_fee'] = $shipping_fee;
			$shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
			$shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
		}
		$smarty->assign('shipping_list', $shipping_list);
	} elseif ('payment' == $step) {
		// 选择支付方式 
		if (exist_real_goods($order_id)) {
			/* 存在实体商品 */
			$region_id_list = array(
			$order['country'], $order['province'], $order['city'], $order['district']
			);
			$shipping_area = shipping_area_info($order['shipping_id'], $region_id_list);
			$pay_fee = ($shipping_area['support_cod'] == 1) ? $shipping_area['pay_fee'] : 0;

			$payment_list = available_payment_list($shipping_area['support_cod'], $pay_fee);
		} else {
			/* 不存在实体商品 */
			$payment_list = available_payment_list(false);
		}

		//if ($order['user_id'] <= 0){
		/* 过滤掉使用余额支付 */
		foreach ($payment_list as $key => $payment) {
			if ($payment['pay_code'] == 'balance') {
				unset($payment_list[$key]);
			}
		}
		//}	
	 
		$smarty->assign('payment_list', $payment_list);
	} elseif ('other' == $step) {
		// 选择包装、贺卡
		$exist_real_goods = exist_real_goods($order_id);
		$smarty->assign('exist_real_goods', $exist_real_goods); 
	    $sql = "SELECT * FROM " . $GLOBALS['os']->table('return_set') . " WHERE type = '2'";
	    $arr = $GLOBALS['db']->getAll($sql);
		$smarty->assign('order_from', $arr);
		
		if ($exist_real_goods) {
			/* 取得包装列表 */
			$smarty->assign('pack_list', pack_list());
			/* 取得贺卡列表 */
			$smarty->assign('card_list', card_list());
		}
	} elseif ('money' == $step) {
		// 费用
		$exist_real_goods = exist_real_goods($order_id);
		$smarty->assign('exist_real_goods', $exist_real_goods);

		/* 取得用户信息 */
		if ($order['user_id'] > 0) {
			$user = user_info($order['user_id']);

			/* 计算可用余额 */
			$smarty->assign('available_user_money', $order['surplus'] + $user['user_money']);

			/* 计算可用积分 */
			$smarty->assign('available_pay_points', $order['integral'] + $user['pay_points']);

			/* 取得用户可用红包 */
			$user_bonus = user_bonus($order['user_id'], $order['goods_amount']);
			if ($order['bonus_id'] > 0) {
				$bonus = bonus_info($order['bonus_id']);
				$user_bonus[] = $bonus;
			}
			$smarty->assign('available_bonus', $user_bonus);	
		}
	} elseif ('invoice' == $step) {
		// 发货后修改配送方式和发货单号
		if (!exist_real_goods($order_id)) {
			die ('Hacking Attemp');
		}

		/* 取得可用的配送方式列表 */
		$region_id_list = array(
			$order['country'], $order['province'], $order['city'], $order['district']
		);
		$shipping_list = available_shipping_list($region_id_list);
		$smarty->assign('shipping_list', $shipping_list);
	}

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_step.tpl');
}

/*------------------------------------------------------ */
//-- 处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'process')
{
	/* 取得参数 func */
	$func = isset($_GET['func']) ? $_GET['func'] : '';

	/* 删除订单商品 */
	if ('drop_order_goods' == $func) {
		/* 检查权限 */
		admin_priv('order_edit');

		/* 取得参数 */
		$rec_id = intval($_GET['rec_id']);
		$step_act = $_GET['step_act'];
		$order_id = intval($_GET['order_id']);

		/* 如果使用库存，且下订单时减库存，则修改库存 */
		if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE) {
			change_goods_inventory($order_id, false);
		}

		/* 删除 */
		$sql = "DELETE FROM " . $os->table('order_goods') . " WHERE rec_id = '$rec_id' LIMIT 1";
		$db->query($sql);

		/* 更新商品总金额和订单总金额 */
		update_order($order_id, array('goods_amount' => order_amount($order_id)));
		update_order_amount($order_id);

		/* 跳回订单商品 */
		os_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
		exit;
	}

	/* 取消刚添加或编辑的订单 */
	elseif ('cancel_order' == $func)
	{
		$step_act = $_GET['step_act'];
		$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
		if ($step_act == 'add') {
			/* 如果是添加，删除订单，返回订单列表 */
			if ($order_id > 0)
			{
				$sql = "DELETE FROM " . $os->table('order_info') .
				" WHERE order_id = '$order_id' LIMIT 1";
				$db->query($sql);
			}
			os_header("Location: order.php?act=list\n");
			exit;
		} else {
			/* 如果是编辑，返回订单信息 */
			os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
			exit;
		}
	}

	/* 编辑订单时由于订单已付款且金额减少而退款 */
	elseif ('refund' == $func)
	{
		/* 处理退款 */
		$order_id       = $_REQUEST['order_id'];
		$refund_type    = $_REQUEST['refund'];
		$refund_note    = $_REQUEST['refund_note'];
		$refund_amount  = $_REQUEST['refund_amount'];
		$order          = order_info($order_id);
		order_refund($order, $refund_type, $refund_note, $refund_amount);

		/* 修改应付款金额为0，已付款金额减少 $refund_amount */
		update_order($order_id, array('order_amount' => 0, 'money_paid' => $order['money_paid'] - $refund_amount));

		/* 返回订单详情 */
		os_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
		exit;
	}

	/* 载入退款页面 */
	elseif ('load_refund' == $func)
	{
		$refund_amount = floatval($_REQUEST['refund_amount']);
		$smarty->assign('refund_amount', $refund_amount);
		$smarty->assign('formated_refund_amount', price_format($refund_amount));

		$anonymous = $_REQUEST['anonymous'];
		$smarty->assign('anonymous', $anonymous); // 是否匿名

		$order_id = intval($_REQUEST['order_id']);
		$smarty->assign('order_id', $order_id); // 订单id

		/* 显示模板 */
		$smarty->assign('ur_here', '退款');
		assign_query_info();
		$guide=lattice_setting('order_refund');
		$smarty->assign('guide',$guide);
		$smarty->display('order_refund.tpl');
	}

	else
	{
		die('invalid params');
	}
}

/*------------------------------------------------------ */
//-- 多订单合并页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_merge')
{
	/* 更新订单承诺发货天数 */
	if ($_CFG['use_promise_delivery']) { auto_update_shipping_days(); }
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '订单合并');
	
	$_LANG['cs'][-1] = '请选择...';
	$smarty->assign('status_list', $_LANG['cs']);   // 订单状态

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);
	
	if($action_name_list == 'all') {
		$smarty->assign('invoice_print',1);
	} elseif(in_array('order_invoice_print',$action_code)) {
		$smarty->assign('invoice_print',1);
	}
	$type = 'order_merge';
	$order_list = order_list($type);
 
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');
	
	/* 载入配送方式 */
	$smarty->assign('shipping_list', shipping_list());
	
	// 增加对配送站搜索的功能
	$sql = 'select s.id,s.station_name from '.$os->table('delivery_station').' as s order by s.id asc';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list',$station_list);
	
	// 结束添加
	if(in_array('order_invoice_print',$action_code)){
		$smarty->assign('b_invoice_print',  1);
	}
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_merge.tpl');
}

/*------------------------------------------------------ */
//-- 两订单合并页面（暂未使用）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'merge')
{
	/* 取得满足条件的订单 */
	$sql = "SELECT o.order_sn, u.user_name " .
		"FROM " . $os->table('order_info') . " AS o " .
		"LEFT JOIN " . $os->table('users') . " AS u ON o.user_id = u.user_id " .
		"WHERE o.user_id > 0 " .
		"AND o.extension_code = '' " . order_query_sql('unprocessed');
	$order_list = $db->getAll($sql);
	$smarty->assign('order_list', $order_list);
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '合并订单');
	$smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => '订单列表'));

	/* 显示模板 */
	assign_query_info();
	$smarty->display('merge_order.tpl');
}

/*------------------------------------------------------ */
//-- 拆分订单页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'split')
{
	$user = '';
	$order_id = $_REQUEST['order_id'];
	$order = order_info($order_id);
	
	/* 取得用户名 */
	if ($order['user_id'] > 0) {
		$user = user_info($order['user_id']);
		if (!empty($user))
		{
			$order['user_name'] = $user['user_name'];
		}
	}

	$order['pay_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']);
	$order['shipping_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']);
	$goods_numb = 0;

	/* 取得订单商品 */
	$goods_list = array();
	$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, o.*, co.color_id,co.color_code,co.color_name,s.size_name,g.goods_number AS storage,o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
    	   " FROM " . $os->table('order_goods') . " AS o ".
    	   " LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
    	   " LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
    	   " LEFT join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id ".
    	   " left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id".
    	   " left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
    	   " left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id ".
    	   "WHERE o.order_id = '$order[order_id]' ";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res)) {
   		/* 虚拟商品支持 */
   		if ($row['is_real'] == 0) {
   			/* 取得语言项 */
   			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
   			if (file_exists($filename)) {
   				include_once($filename);
   				if (!empty($_LANG[$row['extension_code'].'_link'])) {
   					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
   				}
   			}
   		}

   		$row['formated_goods_price']      = price_format($row['goods_price']);
   		//$row['discount_price']    	  	  = round($row['goods_price'] * $discount_rate,2);
   		//$row['formated_discount_price']   = price_format(round($row['goods_price'] * $discount_rate,2));
   		$row['subtotal']         		  = $row['goods_price'] * $row['goods_number'];
   		$row['available_number']		  = $GLOBALS['db']->getOne("SELECT goods_number_available FROM " . $GLOBALS['os']->table('goods_inventory') . " WHERE goods_id='" . $row['goods_id'] . "' AND color_id='" . $row['color_id'] . "' AND size_id='" . $row['size_id'] . "'");

   		//$discount_sub += $row['subtotal'];

   		$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

   		if ($row['extension_code'] == 'package_buy') {
   			$row['package_goods_list'] = get_package_goods($row['goods_id']);
   		}

   		$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" border="0" alt="'.$row['img_name'].'"/>';

   		$row['img_item'] = $img_item;

   		$goods_list[] = $row;
   		$goods_numb++;
    }

    $order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);
    $order['pay_time']      = $order['pay_time'] > 0 ? local_date($_CFG['time_format'], $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
    $order['shipping_time'] = $order['shipping_time'] > 0 ? local_date($_CFG['time_format'], $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];

    $order['status']        = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']] . $process_status;
	$order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];   

    /* 取得订单的来源 */
    if ($order['from_ad'] == 0) {
    	$order['referer'] = empty($order['referer']) ? '来自本站' : $order['referer'];
    } elseif ($order['from_ad'] == -1) {
   		$order['referer'] = '商品站外JS投放' . ' ('.'来自站点：' . $order['referer'].')';
    } else {
   		/* 查询广告的名称 */
   		$ad_name = $db->getOne("SELECT ad_name FROM " .$os->table('ad'). " WHERE ad_id='$order[from_ad]'");
   		$order['referer'] = '广告：' . $ad_name . ' ('.'来自站点：' . $order['referer'].')';
    }
   
    $smarty->assign('goods_list', $goods_list);

    $operable_return_list = operable_return_list($action_code);
    $smarty->assign('operable_return_list', $operable_return_list);

    $b_save = 1;
    $smarty->assign('b_save', $b_save);

    /* 模板赋值 */
    $smarty->assign('ur_here', '拆分订单');
    $smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => '订单列表'));
    $smarty->assign('full_page',        1);

    $smarty->assign('user', $user);
    $smarty->assign('goods_numb', $goods_numb);
    $smarty->assign('order', $order);
   
    /* 显示模板 */
    assign_query_info();
	$smarty->display('split_order.tpl');
}

/*------------------------------------------------------ */
//-- 拆分订单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_split')
{
	$result = array();
	$result = split_order($_POST['order_id'], explode(',', $_POST['split_goods_rec_id']));
	//拆分操作信息
	if ($result['code'] == 0 && $result['new_order_id']) {
    	os_header("Location: order.php?act=info&order_id=" . $result['new_order_id'] . "\n");
	} elseif (!empty($result['message'])) {
		sys_msg($result['message']);
	}
	exit;
}

/*------------------------------------------------------ */
//-- 挂起订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'suspend_list')
{
	/* 自动解挂订单 */
	auto_remove_lock();
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '挂起订单列表');

	//$smarty->assign('status_list', $_LANG['rs']);   // 退货单状态
	$smarty->assign('full_page',        1);

	$arr = array();

	$arr['relating_order_sn']   = trim($_POST['relating_order_sn']);
	$arr['from_reason']  		= trim($_POST['from_reason']);
	$arr['process_mode']        = isset($_POST['process_mode']) ? intval($_POST['process_mode']) : -1;
	$arr['process_status']      = isset($_POST['process_status']) ? intval($_POST['process_status']) : 0;
	$arr['start_time'] 			= trim($_POST['start_time']);
	$arr['end_time']   			= trim($_POST['end_time']);
	
	$smarty->assign("queryPara", $arr);
	
	$order_suspend_list = order_suspend_list($arr);
	
	$smarty->assign('order_suspend_list',   $order_suspend_list['order_suspend_list']);
	$smarty->assign('filter',       $order_suspend_list['filter']);
	$smarty->assign('record_count', $order_suspend_list['record_count']);
	$smarty->assign('page_count',   $order_suspend_list['page_count']);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_suspend_list.tpl');
}

/*------------------------------------------------------ */
//-- 单个挂起处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'suspend')
{
	$order_sn = $_REQUEST['order_sn'];
	if(!empty($order_sn)) {
		$result = suspend_order($order_sn);
		
		/* 清除缓存 */
   		clear_cache_files();
   		/* 提示信息 */
   		if ($result['code'] == 0) {
   			sys_msg('操作成功!');
   		} else {
   			sys_msg('操作失败!');
   		}
	} else {
		/* 提示信息 */
   		sys_msg('对不起，该单据不能进行挂起操作!');
	}
	exit;
}

/*------------------------------------------------------ */
//-- 单个解挂处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_lock')
{
	$order_sn = $_REQUEST['order_sn'];
	if(!empty($order_sn)) {
		$result = remove_suspend_order($order_sn);
		
		/* 清除缓存 */
   		clear_cache_files();
   		/* 提示信息 */
   		$link[] = array('text' => '返回挂起单列表', 'href' => 'order.php?act=suspend_list' );
   		if ($result['code'] == 0) {
   			sys_msg('操作成功!', 0, $link);
   		} else {
   			sys_msg('操作失败!', 0, $link);
   		}
	} else {
		/* 提示信息 */
   		$link[] = array('text' => '返回挂起单列表', 'href' => 'order.php?act=suspend_list' );
   		sys_msg('对不起，该单据没有关联订单，不能进行解挂操作!', 0, $link);
	}
	exit;
}

/*------------------------------------------------------ */
//-- 挂起订单处理页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_suspend_process')
{
	/* 模板赋值 */
	$smarty->assign('ur_here', '挂起订单处理');
	$smarty->assign('action_link', array('href' => 'order.php?act=suspend_list', 'text' => '返回挂起单列表'));
	$smarty->assign('full_page',        1);

	$order_suspend_id = intval($_GET['id']);
	$order_suspend_list = order_suspend_list($arr);
	$sql = 'SELECT * FROM ' . $os->table('order_suspend') . ' WHERE id = '.$order_suspend_id;
	$order_suspend = $db->getRow($sql);
	
	$order_suspend['add_time']   = local_date('Y-m-d H:i', $order_suspend['add_time']);
	$order_suspend['start_time'] = local_date('Y-m-d H:i', $order_suspend['start_time']);
	$order_suspend['end_time']   = local_date('Y-m-d H:i', $order_suspend['end_time']);	
	
	$smarty->assign('order_suspend',   $order_suspend);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_suspend_process.tpl');
}

/*------------------------------------------------------ */
//-- 挂起订单处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'process_suspend')
{
    /* 获得日期信息 */
    $suspend_start_date = '';
    $suspend_end_date   = '';
    
    if (trim($_POST['suspend_start_date']) != '') {
    	$suspend_start_date = local_strtotime($_POST['suspend_start_date']);
    }
    if (trim($_POST['suspend_end_date']) != '') {
    	$suspend_end_date   = local_strtotime($_POST['suspend_end_date']);
    }
	
    /* 对数据的处理 */
    $order_suspend_id = intval($_POST['suspend_id']);
    $process_mode = !empty($_POST['process_mode']) ? intval($_POST['process_mode']) : 0;
	$process_user = $_SESSION['admin_name'];  
	
    $sql = "UPDATE " .$os->table('order_suspend'). " SET ".
           "process_user    = '$process_user', ".
           "process_mode    = '$process_mode', ".
           "start_time      = '$suspend_start_date', ".
           "end_time        = '$suspend_end_date' ".
           "WHERE id        = '$order_suspend_id'";
    $db->query($sql);

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    $link[] = array('text' => '返回挂起单列表', 'href' => 'order.php?act=suspend_list' );
    sys_msg('操作成功!', 0, $link);
}

/*------------------------------------------------------ */
//-- 单个作废处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'invalid')
{
	$order_sn = $_REQUEST['order_sn'];
	if(!empty($order_sn)) {
		$result = invalid_order($order_sn);
		
		/* 清除缓存 */
   		clear_cache_files();
   		/* 提示信息 */
   		if ($result['code'] == 0) {
   			sys_msg('操作成功!');
   		} else {
   			sys_msg('操作失败!');
   		}
	} else {
		/* 提示信息 */
   		sys_msg('对不起，该单据不能进行作废操作!');
	}
	exit;
}

/*------------------------------------------------------ */
//-- 订单打印模板（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'templates')
{
	/* 检查权限 */
	admin_priv('order_templates_edit');

	/* 读入订单打印模板文件 */
	$file_path    = ROOT_PATH. DATA_DIR . '/order_print.html';
	$file_content = file_get_contents($file_path);
	@fclose($file_content);

	include_once(ROOT_PATH."includes/fckeditor/fckeditor.php");

	/* 编辑器 */
	$editor = new FCKeditor('FCKeditor1');
	$editor->BasePath   = "../includes/fckeditor/";
	$editor->ToolbarSet = "Normal";
	$editor->Width      = "95%";
	$editor->Height     = "500";
	$editor->Value      = $file_content;

	$fckeditor = $editor->CreateHtml();
	$smarty->assign('fckeditor', $fckeditor);

	/* 模板赋值 */
	$smarty->assign('ur_here',      '编辑订单打印模板');
	$smarty->assign('action_link',  array('href' => 'order.php?act=list', 'text' => '订单列表'));
	$smarty->assign('act', 'edit_templates');

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_templates.tpl');
}

/*------------------------------------------------------ */
//-- 订单打印模板（提交修改）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_templates')
{
	/* 更新模板文件的内容 */
	$file_name = @fopen('../' . DATA_DIR . '/order_print.html', 'w+');
	@fwrite($file_name, stripslashes($_POST['FCKeditor1']));
	@fclose($file_name);

	/* 提示信息 */
	$link[] = array('text' => '返回订单列表', 'href'=>'order.php?act=list');
	sys_msg('编辑订单打印模板操作成功!', 0, $link);
}

/*------------------------------------------------------ */
//-- 操作订单状态（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'operate')
{
	/* 取得订单id（可能是多个，多个sn）和操作备注（可能没有） */
	$order_id       = $_REQUEST['order_id'];
	$batch          = isset($_REQUEST['batch']); // 是否批处理
	$action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : $_POST['action_note'];

	/* 锁定 */
	if (isset($_POST['lock']))
	{
		$require_note   = false;
		$action         = '锁定';
		$operation      = 'lock';
	}

	/* 解锁 */
	elseif (isset($_POST['unlock']))
	{
		$require_note   = false;
		$action         = '解锁';
		$operation      = 'unlock';
	}

	/* 确认 */
	elseif (isset($_POST['confirm']))
	{
		$require_note   = false;
		$action         = '确认';
		$operation      = 'confirm';
	}

	/* 未确认 */
	elseif (isset($_POST['unconfirm']))
	{
		$require_note   = false;
		$action         = '未确认';
		$operation      = 'unconfirm';
	}

	/* 付款 */
	elseif (isset($_POST['pay']))
	{
		$require_note   = $_CFG['order_pay_note'] == 1;
		$action         = '付款';
		$operation      = 'pay';
	}
	
	/* 未付款 */
	elseif (isset($_POST['unpay']))
	{
		$require_note   = $_CFG['order_unpay_note'] == 1;
		$order          = order_info($order_id);
		if ($order['money_paid'] > 0)
		{
			$show_refund = true;
		}
		$anonymous      = $order['user_id'] == 0;
		$action         = '未付款';
		$operation      = 'unpay';
	}
	
	/* 发货 */
	elseif (isset($_POST['ship']))
	{
		$require_note   = $_CFG['order_ship_note'] == 1;
		$show_invoice_no= true;
		$action         = '发货';
		$operation      = 'ship';
	}
	
	/* 未发货 */
	elseif (isset($_POST['unship']))
	{
		$require_note   = $_CFG['order_ship_note'] == 1;
		$action         = '未发货';
		$operation      = 'unship';
	}
	
	/* 追单 */
	elseif (isset($_POST['chase']))
	{
		$require_note      = $_CFG['order_ship_note'] == 1;
		$show_chase_option = true;
		$action            = '追单';
		$operation         = 'chase';
	}
	
	/* 结算 */
	elseif (isset($_POST['pay_finish']))
	{
		$require_note   = $_CFG['order_ship_note'] == 1;
		$action         = '结算';
		$operation      = 'pay_finish';
	}

	/* 取消 */
	elseif (isset($_POST['cancel']))
	{
		$require_note   = $_CFG['order_cancel_note'] == 1;
		$action         = '取消';
		$operation      = 'cancel';
		$show_cancel_note   = true;
		$order          = order_info($order_id);
		if ($order['money_paid'] > 0)
		{
			$show_refund = true;
		}
		$anonymous      = $order['user_id'] == 0;
	}

	/* 作废 */
	elseif (isset($_POST['invalid']))
	{
		$require_note   = $_CFG['order_invalid_note'] == 1;
		$action         = '作废';
		$operation      = 'invalid';
	}
	
	/* 退货 */
	elseif (isset($_POST['return']))
	{
		$require_note   = $_CFG['order_return_note'] == 1;
		$order          = order_info($order_id);
		if ($order['money_paid'] > 0)
		{
			$show_refund = true;
		}
		$anonymous      = $order['user_id'] == 0;
		$action         = '退货';
		$operation      = 'return';
	}
	
	/* 挂起 */
	elseif (isset($_POST['suspend']))
	{
		$require_note   = true;
		$show_suspend_note = true;
		$action         = '挂起';
		$operation      = 'suspend';
	}
	
	/* 解挂 */
	elseif (isset($_POST['remove_suspend']))
	{
		$require_note   = true;
		$action         = '解挂';
		$operation      = 'remove_suspend';
	}
	
	/* 配货 */
	elseif (isset($_POST['range']))
	{
		$require_note   = false;
		$action         = '配货';
		$operation		= 'range';
		//$operation    = $batch ? 'batch_range' : 'unbatch_range';
	}
	
	/* 未配货 */
	elseif (isset($_POST['unrange']))
	{
		$require_note   = false;
		$action         = '未配货';
		$operation      = 'unrange';
	}
	
	/* 设为问题单 */
	elseif (isset($_REQUEST['question']))
	{
		$require_note   = true;
		$show_question_reason = true;
		$question_reasons = get_question_reason();
		$action         = '设为问题单';
		$operation      = 'question';
	}
	
	/* 返回正常订单 */
	elseif (isset($_REQUEST['remove_question']))
	{
		$require_note   = false;
		$action         = '返回正常订单';
		$operation      = 'remove_question';
	}
	
	/* 缺货处理 */
	elseif (isset($_POST['out_handle']))
	{
		$require_note   = false;
		$action         = '缺货处理';
		$operation      = 'out_handle';
		header("Location: order.php?act=order_out_process&order_id=$order_id");
		exit;
	}
	
	/* 订单合并 */
	elseif (isset($_POST['merge']))
	{
		$require_note   = false;
		$action         = '订单合并';
		$operation      = 'merge';
	}
	
	/* 指派 */
	elseif (isset($_POST['assign']))
	{
		/* 取得参数 */
		$new_agency_id  = isset($_POST['agency_id']) ? intval($_POST['agency_id']) : 0;
		if ($new_agency_id == 0) {
			sys_msg('请选择办事处！');
		}

		/* 查询订单信息 */
		$order = order_info($order_id);

		/* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
		$sql = "SELECT agency_id FROM " . $os->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
		$admin_agency_id = $db->getOne($sql);
		if ($admin_agency_id > 0) {
			if ($order['agency_id'] != $admin_agency_id) {
				sys_msg('对不起,您没有执行此项操作的权限!');
			}
		}

		/* 修改订单所属的办事处 */
		if ($new_agency_id != $order['agency_id']) {
			$sql = "UPDATE " . $os->table('order_info') . " SET agency_id = '$new_agency_id' " .
				"WHERE order_id = '$order_id' LIMIT 1";
			$db->query($sql);
		}

		/* 操作成功 */
		$links[] = array('href' => 'order.php?act=list&' . list_link_postfix(), 'text' => '订单列表');
		sys_msg('操作成功', 0, $links);
	}
	
	/* 删除 */
	elseif (isset($_POST['remove']))
	{
		$require_note = false;
		$operation = 'remove';
		if (!$batch) {
			/* 检查能否操作 */
			$order = order_info($order_id);
			$operable_list = operable_list($order,$action_code);
			if (!isset($operable_list['remove'])) {
				die('Access Denied');
			}

			/* 删除订单 */
			$db->query("DELETE FROM ".$os->table('order_info'). " WHERE order_id = '$order_id'");
			$db->query("DELETE FROM ".$os->table('order_goods'). " WHERE order_id = '$order_id'");
			$db->query("DELETE FROM ".$os->table('order_action'). " WHERE order_id = '$order_id'");
			$db->query("DELETE FROM ".$os->table('order_suspend'). " WHERE relating_order_id = '$order_id'");
	
			/* todo 记录日志 */
			admin_log($order['order_sn'], 'order_remove', 'order');

			/* 返回 */
			sys_msg('订单删除成功。', 0, array(array('href'=>'order.php?act=list&' . list_link_postfix(), 'text' => '返回订单列表')));
		}
	}
	
	/* 批量打印订单 */
	elseif (isset($_POST['print']))
	{
		if (empty($_POST['order_id'])) {
			sys_msg('请选择您要操作的订单');
		}

		/* 赋值公用信息 */
		$smarty->assign('shop_name',    $_CFG['shop_name']);
		$smarty->assign('shop_url',     $os->url());
		$smarty->assign('shop_address', $_CFG['shop_address']);
		$smarty->assign('service_phone',$_CFG['service_phone']);
		$smarty->assign('print_time',   local_date($_CFG['time_format']));
		$smarty->assign('action_user',  $_SESSION['admin_name']);
		$html = '';
		$order_sn_list = explode(',', $_POST['order_id']);

		foreach ($order_sn_list as $order_sn) {
			/* 取得订单信息 */
			$order = order_info(0, $order_sn);
			if (empty($order)) {
				continue;
			}

			/* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
			$sql = "SELECT agency_id FROM " . $os->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
			$agency_id = $db->getOne($sql);
			if ($agency_id > 0) {
				if ($order['agency_id'] != $agency_id) {
					continue;
				}
			}

			/* 取得用户名 */
			if ($order['user_id'] > 0) {
				$user = user_info($order['user_id']);
				if (!empty($user)) {
					$order['user_name'] = $user['user_name'];
				}
			}

			/* 取得区域名 */
			$sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
				"'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
				"FROM " . $os->table('order_info') . " AS o " .
				"LEFT JOIN " . $os->table('region') . " AS c ON o.country = c.region_id " .
				"LEFT JOIN " . $os->table('region') . " AS p ON o.province = p.region_id " .
				"LEFT JOIN " . $os->table('region') . " AS t ON o.city = t.region_id " .
				"LEFT JOIN " . $os->table('region') . " AS d ON o.district = d.region_id " .
				"WHERE o.order_id = '$order[order_id]'";
			$order['region'] = $db->getOne($sql);

			/* 其他处理 */
			$order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);
			$order['pay_time']      = $order['pay_time'] > 0 ? local_date($_CFG['time_format'], $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
			$order['shipping_time'] = $order['shipping_time'] > 0 ? local_date($_CFG['time_format'], $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];
			$order['status']        = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']];
			$order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

			/* 此订单的发货备注(此订单的最后一条操作记录) */
			$sql = "SELECT action_note FROM " . $os->table('order_action').
				" WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC";
			$order['invoice_note'] = $db->getOne($sql);

			/* 参数赋值：订单 */
			$smarty->assign('order', $order);

			/* 取得订单商品 */
			$goods_list = array();
			$goods_attr = array();
			$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, o.*,co.*,s.size_name,g.goods_number AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
				"FROM " . $os->table('order_goods') . " AS o " .
				"LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
				"LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
				"LEFT JOIN " . $os->table('color') . " AS co on o.color_id = co.color_id " .
				"LEFT JOIN " . $os->table('goods_color') . " AS gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id " .
				 " left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
				"LEFT JOIN " . $os->table('size') . " AS s on o.size_id = s.size_id " .
				"WHERE o.order_id = '$order[order_id]' ";
			$res = $db->query($sql);

			while ($row = $db->fetchRow($res)) {
				/* 虚拟商品支持 */
				if ($row['is_real'] == 0) {
					/* 取得语言项 */
					$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
					if (file_exists($filename)) {
						include_once($filename);
						if (!empty($_LANG[$row['extension_code'].'_link'])) {
							$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
						}
					}
				}

				$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
				$row['formated_goods_price']    = price_format($row['goods_price']);

				$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
				$goods_list[] = $row;
			}

			$attr = array();
			$arr  = array();
			foreach ($goods_attr AS $index => $array_val) {
				foreach ($array_val AS $value) {
					$arr = explode(':', $value);//以 : 号将属性拆开
					$attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
				}
			}

			$smarty->assign('goods_attr', $attr);
			$smarty->assign('goods_list', $goods_list);

			order_print_log($order_sn,1);

			$smarty->template_dir = '../' . DATA_DIR;
			$html .= $smarty->fetch('order_print.html') .
			'<div style="PAGE-BREAK-AFTER:always"></div>';
		}

		echo $html;
		exit;
	}

	/* 打印配货单 */
	elseif (isset($_POST['print_invoice']))
	{
		if (empty($_POST['order_id'])) {
			sys_msg('请选择您要操作批次的订单');
		}

		/* 赋值公用信息 */
		$smarty->assign('print_time',   local_date($_CFG['time_format']));
		$smarty->assign('action_user',  $_SESSION['admin_name']);

		$html = '';
		$order_sn_list = explode(',', $_POST['order_id']);

		$invoice_id_list = array();

		foreach ($order_sn_list as $order_sn) {
			/* 取得订单信息 */
			$order = order_info(0, $order_sn);
			if (empty($order)) {
				continue;
			}
			array_push($invoice_id_list, $order['order_id']);
		}

		// 根据已打印订单中的订单列表来打印相应的配货单
		$order_ids = implode(',',$invoice_id_list);
		if ($order_ids != '') {
			// 取得配货 货号、商品名称、商品颜色、商品尺寸、商品库位、商品数量
			$sql = 'select oi.order_sn,og.goods_sn,og.goods_name,c.color_code,s.size_code,s.size_note,gc.color_name,s.size_name,g.storage_location,sum(og.goods_number) as total from '.$os->table('order_goods').' as og,'.$os->table('goods').' as g,'.$os->table('goods_size').' as gs,'.$os->table('goods_color').' as gc,'.$os->table('order_info').' as oi ,'.$os->table('color').' as c ,'.$os->table('size').' as s '.
				' where og.goods_id = g.goods_id and c.color_id = gc.color_id and s.size_id = gs.size_id and og.size_id = gs.size_id and og.goods_id = gs.goods_id and og.goods_id = gc.goods_id and og.color_id = gc.color_id and og.order_id in ('.$order_ids.')'.' and og.order_id = oi.order_id and oi.shipping_status <> '.SS_SHIPPED.
	
				' group by og.goods_id,og.size_id,og.color_id'.
				' order by og.goods_id';
			$invoice_list = $db->getAll($sql);
			
			/************** 处理成展示用的格式 ******************************************************/
			//取出款号
			$arr_sns = array();
			foreach ($invoice_list as $key=>$sns ) {
				if (!in_array($sns['goods_sn'],$arr_sns)) {
					array_push($arr_sns,$sns['goods_sn']);
				}
			}
			//取出所有尺码
			$arr_sizes =  array();
			foreach ($invoice_list as $key=>$sku ) {
				if (!in_array($sku['size_name'],$arr_sizes)) {
					array_push($arr_sizes,$sku['size_name']);
				}
			}
			
			/*****************九牧王特殊需求 开始*************************************/
			
//			$arr_sizes =  array();
//			foreach ($invoice_list as $key=>$sku ){
//				if(!in_array($sku['size_note'],$arr_sizes)){
//					array_push($arr_sizes,$sku['size_note']);
//				}
//			}
			
			asort($arr_sizes);

			$str_size_names = '';
			$temp_i = 0;
			foreach ($arr_sizes as $value) {
				if($temp_i == 0) {
					$str_size_names .= "'".$value."'";
				} else {
					$str_size_names .= ",'".$value."'";
				}
				$temp_i++;
			}
			
			$sql = "select  size_note from open_size where size_name in(".$str_size_names.") order by size_name";

			$arr_sizes_notes = array();
			$arr_notes = array();
			$arr_sizes_notes = $db->getAll($sql);
			foreach ($arr_sizes_notes as $notes) {
				array_push($arr_notes,$notes['size_note']);
			}
			foreach ($arr_sizes as $mysize) {
				//取出对应的size_note
				foreach ($invoice_list as $key=>$sku2 ) {
					if($sku2['size_name'] == $mysize) {
						if(!in_array($sku2['size_note'],$arr_sizes_notes)) {
							array_push($arr_sizes_notes,$sku2['size_note']);
						}
					}
				}
			}
			
			/******************九牧王特殊需求 结束************************************/
			
			//取出一个款号所对应的尺码组
			$goods_sizes = array();
			foreach ($arr_sns as $goods_sn ) {
				foreach ($arr_sizes as $size) {
					$goods_sizes[$goods_sn][$size] = '';
					//判断该款号对应的尺码是否有值
					foreach ($invoice_list as $key=>$sku) {
						if($sku['goods_sn'] == $goods_sn && $sku['size_name'] == $size) {
							$goods_sizes[$goods_sn][$size] = $sku['total'];
						}
					}
				}
			}
			//$smarty->assign('arr_sizes',$arr_sizes);
			//九牧王特殊需求，将size_note作为size_name来调用。
			$smarty->assign('arr_sizes',$arr_notes);
			$smarty->assign('goods_sizes',$goods_sizes);

			/*************************************************************************************/
			$smarty->assign('invoice_list',$invoice_list);
			$smarty->assign('print_time',   local_date($_CFG['time_format']));
			$smarty->assign('action_user',  $_SESSION['admin_name']);

			// 打印好配货单后,将该订单的配货标识置为1
			$sql = "UPDATE " . $os->table('order_info') .
				" SET invoice_status = 1".
				" WHERE order_id IN (".$order_ids.")";
			$db->query($sql);

			foreach ($invoice_list as $invoice) {
				order_print_log($invoice['order_sn'],2);
			}
			$sql = "SELECT sk_id,sk_name FROM ".$os->table('storekeeper')." ORDER BY add_time DESC";
			$result = $db->query($sql);
			$arr = array();
			while ($row = $db->fetchRow($result)) {
				$arr[$row['sk_id']] = $row['sk_name'];
			}
			$smarty->assign('storekeeper_list', $arr);
		}
		
		$smarty->template_dir = '../' . DATA_DIR;
		$smarty->display('invoice_print.html');
		exit;
	}
	
	/* 直接处理还是跳到详细页面 */
	if (($require_note && $action_note == '') || isset($show_invoice_no) || isset($show_refund)) {
		/* 模板赋值 */
		$order_ids   = $_REQUEST['order_id'];        // 订单id（逗号格开的多个订单id）
		$smarty->assign('order_id', $order_ids);
		$smarty->assign('require_note', $require_note); // 是否要求填写备注
		$smarty->assign('action_note', $action_note);   // 备注
		$smarty->assign('show_cancel_note', isset($show_cancel_note)); // 是否显示取消原因
		$smarty->assign('show_suspend_note', isset($show_suspend_note)); // 是否显示挂起原因
		$smarty->assign('show_invoice_no', isset($show_invoice_no)); // 是否显示发货单号
		$smarty->assign('show_chase_option', isset($show_chase_option)); // 是否显示追单状态
		$smarty->assign('show_refund', isset($show_refund)); // 是否显示退款
		$smarty->assign('show_question_reason', isset($show_question_reason)); // 是否显示问题单原因
		$smarty->assign('question_reasons', $question_reasons); // 问题单原因数组
		$smarty->assign('anonymous', isset($anonymous) ? $anonymous : true); // 是否匿名
		$smarty->assign('order_id', $order_id); // 订单id
		$smarty->assign('batch', $batch);   // 是否批处理
		$smarty->assign('operation', $operation); // 操作

		/* 显示模板 */
		$smarty->assign('ur_here', '订单操作：' . $action);
		assign_query_info();
		$smarty->display('order_operate.tpl');
	} else {
		/* 直接处理 */
		if (!$batch) {
			/* 一个订单 */
			os_header("Location: order.php?act=operate_post&order_id=" . $order_id .
			"&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
			exit;
		} else {
			/* 多个订单 */
			os_header("Location: order.php?act=batch_operate_post&order_id=" . $order_id .
			"&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
			exit;
		}
	}
}

/*------------------------------------------------------ */
//-- 操作订单状态（处理批量提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch_operate_post')
{
	/* 取得参数 */
	$order_id    = $_REQUEST['order_id'];        // 订单id（逗号格开的多个订单id）
	$operation   = $_REQUEST['operation'];       // 订单操作
	$action_note = $_REQUEST['action_note'];     // 操作备注

	$order_id_list = explode(',', $order_id);

	/* 初始化处理的订单sn */
	$sn_list = array();
	$sn_not_list = array();

	/* 确认 */
	if ('confirm' == $operation) {
		$valid_ids = array();
		$valid_res = array();
		$invalid_res = array();
		if ($order_id) {
			$valid_ids = $GLOBALS['db']->getCol("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE user_id>'0' AND order_sn IN ( $order_id ) AND order_status = '" . OS_UNCONFIRMED . "' AND process_status = '" . OPS_NORMAL . "' ");
			if (count($valid_ids) > 0) { $not_in_str = " AND order_id NOT IN ( " . implode(',', $valid_ids) . " ) "; }
			else { $not_in_str = ''; }
			$invalid_res = $GLOBALS['db']->getCol("SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE user_id>'0' AND order_sn IN ( $order_id ) $not_in_str ");
			$valid_res = manage_goods_inventory($valid_ids, 'confirm');
		} else {
			sys_msg('请先勾选需要确认的订单。');
			exit;
		}
		/* 修改订单状态、发邮件 */
		if (is_array($valid_res['success_sns'])) {
			foreach($valid_res['success_sns'] as $key => $val) {
				$order = order_info(0, $val);
				/* 标记订单为已确认 */
				update_order($order['order_id'], array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
				update_order_amount($order['order_id']);
				order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note);
				/* 更新计划发货时间 */
				auto_update_shipping_delivery($order['order_id']);
				/* 发送邮件 */
				if ($_CFG['send_confirm_email'] == '1') {
					$tpl = get_mail_template('order_confirm');
					$order['formated_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
					$smarty->assign('order', $order);
					$smarty->assign('shop_name', $_CFG['shop_name']);
					$smarty->assign('send_date', local_date($_CFG['date_format']));
					$smarty->assign('sent_date', local_date($_CFG['date_format']));
					$content = $smarty->fetch('str:' . $tpl['template_content']);
					send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
				}
			}
		}
		/* 操作提示信息 */
		$sys_msg_type = 0;
		if ($sys_msg_type) { //提示页面
			$smarty->assign('ur_here', '确认提示信息');
			$smarty->assign('success_sns', $valid_res['success_sns']);
			$smarty->assign('error_sns', $valid_res['error_sns']);
			$smarty->assign('out_sns', $valid_res['out_sns']);
			$smarty->assign('other_sns', $invalid_res);
			$smarty->display('confirm_message.tpl');
			exit;
		} else { //输出信息并跳转
			foreach($valid_res['success_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="green">订单 ' . $val . ' 确认成功。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 确认成功。</font>';
				}
			}
			foreach($valid_res['error_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于全部缺货，确认失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于全部缺货，确认失败。</font>';
				}
			}
			foreach($valid_res['out_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于部分缺货，配货失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于部分缺货，配货失败。</font>';
				}
			}
			foreach($invalid_res as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 状态不是 未确认、正常。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 状态不是 未确认、正常。</font>';
				}
			}
			if(!empty($message)) {
				sys_msg($message);
				exit;
			}
		}
		$sn_str = '以下订单无法设置为确认状态';
	}
	
	/* 结算 */
	elseif ('pay_finish' == $operation)
	{
		foreach($order_id_list as $id_order) {
			$sql = "SELECT * FROM " . $os->table('order_info') .
				" WHERE order_sn = '$id_order'";
			$order = $db->getRow($sql);

			if ($order) {
				$order_id = $order['order_id'];
				update_order($order_id, array('order_status' => OS_FINISH, 'pay_status' => PS_PAYED_FINISH));
				order_action($order['order_sn'], OS_FINISH, $order['shipping_status'], PS_PAYED_FINISH, $action_note);	
				order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], PS_PAYED, $action_note);					
				$sn_list[] = $order['order_sn'];
			} else {
				$sn_not_list[] = $id_order;
			}
		}
		$sn_str = '以下订单无法设置为结算状态';
	}	
	
	/* 无效 */
	elseif ('invalid' == $operation)
	{
		foreach($order_id_list as $id_order) {
			$sql = "SELECT * FROM " . $os->table('order_info') .
				" WHERE order_sn = $id_order" . order_query_sql('unpay_unship');
			$order = $db->getRow($sql);

			if($order) {
				/* 检查能否操作 */
				$operable_list = operable_list($order,$action_code);
				if (!isset($operable_list[$operation])) {
					$sn_not_list[] = $id_order;
					continue;
				}
				$order_id = $order['order_id'];

				update_order($order_id, array('order_status' => OS_INVALID));
				order_action($order['order_sn'], OS_INVALID, $order['shipping_status'], $order['pay_status'], $action_note);
				update_order_lock_status($order_id,0);
				$order_status = $order['order_status'];
				
				/* 库存处理 */
				manage_goods_inventory($order['order_id'], 'invalid');
				
				/* 发送邮件 */
				if ($_CFG['send_invalid_email'] == '1') {
					$tpl = get_mail_template('order_invalid');
					$smarty->assign('order', $order);
					$smarty->assign('shop_name', $_CFG['shop_name']);
					$smarty->assign('send_date', local_date($_CFG['date_format']));
					$smarty->assign('sent_date', local_date($_CFG['date_format']));
					$content = $smarty->fetch('str:' . $tpl['template_content']);
					send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
				}

				/* 退还用户余额、积分、红包 */
				return_user_surplus_integral_bonus($order);

				$sn_list[] = $order['order_sn'];
			} else {
				$sn_not_list[] = $id_order;
			}
		}
		$sn_str = '以下订单无法设置为无效';
	}
	
	/* 取消 */
	elseif ('cancel' == $operation)
	{
		foreach($order_id_list as $id_order) {
			$sql = "SELECT * FROM " . $os->table('order_info') .
				" WHERE order_sn = $id_order" . order_query_sql('unpay_unship');
			$order = $db->getRow($sql);
			if($order) {
				/* 检查能否操作 */
				$operable_list = operable_list($order,$action_code);
				if (!isset($operable_list[$operation])) {
					$sn_not_list[] = $id_order;
					continue;
				}
				$order_id = $order['order_id'];

				/* 库存处理 */
				manage_goods_inventory($order['order_id'], 'cancel');
				
				$cancel_note = trim($_REQUEST['cancel_note']);
				update_order($order_id, array('order_status' => OS_CANCELED, 'to_buyer' => $cancel_note));
				update_order_lock_status($order_id,0);
				order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], $order['pay_status'], $action_note);

				/* 发送邮件 */
				if ($_CFG['send_cancel_email'] == '1') {
					$tpl = get_mail_template('order_cancel');
					$smarty->assign('order', $order);
					$smarty->assign('shop_name', $_CFG['shop_name']);
					$smarty->assign('send_date', local_date($_CFG['date_format']));
					$smarty->assign('sent_date', local_date($_CFG['date_format']));
					$content = $smarty->fetch('str:' . $tpl['template_content']);
					send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
				}

				/* 退还用户余额、积分、红包 */
				//return_user_surplus_integral_bonus($order);

				$sn_list[] = $order['order_sn'];
			} else {
				$sn_not_list[] = $id_order;
			}
		}
		$sn_str = '以下订单无法取消';
	}
	
	/* 移除 */
	elseif ('remove' == $operation)
	{
		foreach ($order_id_list as $id_order) {
			/* 检查能否操作 */
			$order = order_info(0, $id_order);
			$operable_list = operable_list($order,$action_code);
			if (!isset($operable_list['remove'])) {
				$sn_not_list[] = $id_order;
				continue;
			}

			/* 库存处理 */
			manage_goods_inventory($order['order_id'], 'remove');
			
			/* 删除订单 */
			$db->query("DELETE FROM ".$os->table('order_info'). " WHERE order_id = '$order[order_id]'");
			$db->query("DELETE FROM ".$os->table('order_goods'). " WHERE order_id = '$order[order_id]'");
			$db->query("DELETE FROM ".$os->table('order_action'). " WHERE order_id = '$order[order_id]'");
			$db->query("DELETE FROM ".$os->table('order_suspend'). " WHERE order_id = '$order[relating_order_id]'");

			/* todo 记录日志 */
			admin_log($order['order_sn'], 'order_remove', 'order');

			$sn_list[] = $order['order_sn'];
		}
		$sn_str = '以下订单无法被移除';
	}
	
	/* 挂起 */
	elseif ('suspend' == $operation)
	{
		$arr = array();
		$arr['action_note'] = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
		$arr['suspend_note'] = isset($_REQUEST['suspend_note']) ? trim($_REQUEST['suspend_note']) : '';
		$arr['suspend_end_date'] = isset($_REQUEST['suspend_end_date']) ? local_strtotime($_REQUEST['suspend_end_date']) : '';
		$result = suspend_orders($order_id, '', $arr);
		if (!is_array($result) && !$result) { sys_msg('请先勾选需要挂起的订单。'); exit; }
		
		/* 操作提示信息 */
		$sys_msg_type = 0;
		if ($sys_msg_type) { //提示页面
			$smarty->assign('ur_here', '挂起提示信息');
			$smarty->assign('success_sns', $result['success_sns']);
			$smarty->assign('error_sns', $result['error_sns']);
			$smarty->assign('other_sns', $result['invalid_sns']);
			$smarty->display('suspend_message.tpl');
			exit;
		} else { //输出信息并跳转
			foreach($result['success_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="green">订单 ' . $val . ' 挂起成功。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 挂起成功。</font>';
				}
			}
			foreach($result['error_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于数据库问题，挂起失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于数据库问题，挂起失败。</font>';
				}
			}
			foreach($result['invalid_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 不能被挂起。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 不能被挂起。</font>';
				}
			}
			if(!empty($message)) {
				sys_msg($message);
				exit;
			}
		}
		$sn_str = '以下订单无法被挂起';
	}
	
	/* 解挂 */
	elseif ('remove_suspend' == $operation)
	{
		$action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
		$result = remove_suspend_orders($order_id, '', $action_note);
		if (!is_array($result) && !$result) { sys_msg('请先勾选需要解挂的订单。'); exit; }
		
		/* 操作提示信息 */
		$sys_msg_type = 0;
		if ($sys_msg_type) { //提示页面
			$smarty->assign('ur_here', '解挂提示信息');
			$smarty->assign('success_sns', $result['success_sns']);
			$smarty->assign('error_sns', $result['error_sns']);
			$smarty->assign('other_sns', $result['invalid_sns']);
			$smarty->display('remove_lock_message.tpl');
			exit;
		} else { //输出信息并跳转
			foreach($result['success_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="green">订单 ' . $val . ' 解挂成功。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 解挂成功。</font>';
				}
			}
			foreach($result['error_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于数据库问题，解挂失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于数据库问题，解挂失败。</font>';
				}
			}
			foreach($result['invalid_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 不是已挂起订单。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 不是已挂起订单。</font>';
				}
			}
			if(!empty($message)) {
				sys_msg($message);
				exit;
			}
		}
		$sn_str = '以下订单无法被解挂';
	}
	
	/* 设为问题单 */
	elseif ('question' == $operation)
	{
		$action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
		$result = question_orders($order_id, $_REQUEST['reason_id'], '', $action_note);
		if (!is_array($result) && !$result) { sys_msg('请先勾选需要设为问题单的订单。'); exit; }
		
		/* 操作提示信息 */
		$sys_msg_type = 0;
		if ($sys_msg_type) { //提示页面
			$smarty->assign('ur_here', '设为问题单提示信息');
			$smarty->assign('success_sns', $result['success_sns']);
			$smarty->assign('error_sns', $result['error_sns']);
			$smarty->assign('other_sns', $result['invalid_sns']);
			$smarty->display('question_message.tpl');
			exit;
		} else { //输出信息并跳转
			foreach($result['success_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="green">订单 ' . $val . ' 设为问题单成功。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 设为问题单成功。</font>';
				}
			}
			foreach($result['error_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于数据库问题，设为问题单失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于数据库问题，设为问题单失败。</font>';
				}
			}
			foreach($result['invalid_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 状态不能是 已完成、已拆分、已合并、无效、已发货。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 状态不能是 已完成、已拆分、已合并、无效、已发货。</font>';
				}
			}
			if(!empty($message)) {
				sys_msg($message);
				exit;
			}
		}
		$sn_str = '以下订单无法被设为问题单';
	}

	/* 返回正常订单 */
	elseif ('remove_question' == $operation)
	{
		foreach ($order_id_list as $id_order) {
			$result = remove_question_order($id_order);
		}
		sys_msg('批量返回正常订单成功。');
		exit;
		
		$sn_str = '以下订单无法返回正常订单';
	}
	
	/* 配货中间界面（暂未使用） */
	elseif ('batch_range' == $operation) {
		$order_sns = $order_id_list;
		$success_ids = array();
		$success_sns = array();
		$error_sns = array();
		$accept = 1;
		if (count($order_sns) <= 0) {
			$note = '请先选择需要配货的订单。';	
			$accept = 0;	
		} else {
			foreach ($order_sns as $key => $val) {
				$order = order_info(0, $val);
				$result = check_goods_inventory($order['order_id']);
				if ($result['code'] == 0) {
					array_push($success_ids, $order['order_id']);
					array_push($success_sns, $order['order_sn']);
				} else {
					array_push($error_sns, $order['order_sn']);
				}
			}
		}
		
		if ($accept) {
			if (count($success_sns) <= 0) {
				$note .= '<br/><br/>订单 ' . implode(',', $error_sns) . ' 不能配货，请检查各订单商品的可用现货库存。';
				$accept = 0;
			} elseif (count($success_sns) == count($order_sns)) {
				$note .= '<br/><br/>订单 ' . implode(',', $success_sns) . ' 可以配货。';
			} else {
				$note .= '<br/><br/>订单 ' . implode(',', $success_sns) . ' 可以配货。<br/><br/>订单 ' . implode(',', $error_sns) . ' 不能配货，请检查各订单商品的可用现货库存。';
			}
		}
		
		$smarty->assign('ur_here', '订单配货检查');
		$smarty->assign('note', $note);
		$smarty->assign('accept', $accept);
		$smarty->assign('order_id', $order_id);
		$smarty->assign('operation', 'range');
		$smarty->assign('batch', 1);
		
		$smarty->display('order_note.tpl');
		exit;
	}
	
	/* 配货 */
	elseif ('range' == $operation) {
		$result = range_orders($order_id);
		if (!is_array($result) && !$result) { sys_msg('请先勾选需要配货的订单。'); exit; }
		
		/* 操作提示信息 */
		$sys_msg_type = 1;
		if ($sys_msg_type) { //提示页面
			$smarty->assign('ur_here', '配货提示信息');
			$smarty->assign('success_sns', $result['success_sns']);
			$smarty->assign('error_sns', $result['error_sns']);
			$smarty->assign('out_sns', $result['out_sns']);
			$smarty->assign('other_sns', $result['invalid_sns']);
			$smarty->display('range_message.tpl');
			exit;
		} else { //输出信息并跳转
			foreach($result['success_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="green">订单 ' . $val . ' 配货成功。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 配货成功。</font>';
				}
			}
			foreach($result['error_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于全部缺货，配货失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于全部缺货，配货失败。</font>';
				}
			}
			foreach($result['out_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 由于部分缺货，配货失败。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 由于部分缺货，配货失败。</font>';
				}
			}
			foreach($result['other_sns'] as $key => $val) {
				if (empty($message) && $key == 0) {
					$message = '<font color="red">订单 ' . $val . ' 状态不是 已确认或已付款、正常、未配货。</font>';
				} else {
					$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="red">订单 ' . $val . ' 状态不是 已确认或已付款、正常、未配货。</font>';
				}
			}
			if(!empty($message)) {
				sys_msg($message);
				exit;
			}
		}
		$sn_str = '以下订单无法设置为已配货状态';
	}
	
	/* 返回待配货 */
	elseif ('unrange' == $operation) {
		$valid_ids = array();
		$valid_res = array();
		$invalid_res = array();
		if ($order_id) {
			$valid_ids = $GLOBALS['db']->getCol("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE user_id>'0' AND order_sn IN ( $order_id ) AND range_status = '" . ORS_CONFIRMED . "' AND process_status = '" . OPS_NORMAL . "' ");
			if (count($valid_ids) > 0) { $not_in_str = " AND order_id NOT IN ( " . implode(',', $valid_ids) . " ) "; }
			else { $not_in_str = ''; }
			$invalid_res = $GLOBALS['db']->getCol("SELECT order_sn FROM " . $GLOBALS['os']->table('order_info') . " WHERE user_id>'0' AND order_sn IN ( $order_id ) $not_in_str ");
			$valid_res = manage_goods_inventory($valid_ids, 'unrange');
		} else {
			sys_msg('请先勾选需要返回待配货的订单。');
			exit;
		}
		/* 修改订单状态 */
		if (is_array($valid_res['success_sns'])) {
			foreach($valid_res['success_sns'] as $key => $val) {
				$order = order_info(0, $val);
				/* 标记订单为待配货 */
				update_order($order['order_id'], array('range_status' => ORS_UNCONFIRMED));
				order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], ORS_UNCONFIRMED);
				/* 清除配货未成功记录 */
				$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'");
				/* 更新计划发货时间 */
				auto_update_shipping_delivery($order['order_id']);
			}
		}
		/* 操作提示信息 */
		foreach($valid_res['success_sns'] as $key => $val) {
			if (empty($message) && $key == 0) {
				$message = '<font color="green">订单 ' . $val . ' 返回待配货状态成功。</font>';
			} else {
				$message .= '<br/>&nbsp;&nbsp;&nbsp;<font color="green">订单 ' . $val . ' 返回待配货状态成功。</font>';
			}
		}
		if(!empty($message)) {
			sys_msg($message);
			exit;
		}
		$sn_str = '以下订单无法设置为确认状态';
	}
	
	/* 多订单合并中间页面 */
	elseif ('merge' == $operation) {
		$order_sns = $order_id_list;
		$success_sns = array();
		$error_sns = array();
		$main_order = array();
		if (count($order_sns) <= 1) {
			$note = '<font color="red">请至少勾选两张以上的订单进行合并。</font>';
			$accept = 0;			
		} else {
			foreach ($order_sns as $key => $val) {
				$cur_order = order_info(0, $val);
				if ($key == 0) { //以第一张订单为主
					$main_order = $cur_order;
					if (($main_order['order_status'] != OS_UNCONFIRMED && $main_order['order_status'] != OS_CONFIRMED)
						|| ($main_order['pay_status'] != PS_UNPAYED && $main_order['pay_status'] != PS_PAYED)
						|| ($main_order['shipping_status'] != SS_UNSHIPPED)) { //检查主订单状态、支付状态、发货状态
						$note = '<font color="red">请确保第一张订单的状态为 已确认或未确认、已付款或未付款、未发货。</font>';
						$accept = 0;
						break;
					} else {
						$note = '主订单 ' . $main_order['order_sn'];
						$accept = 1;
					}
				} else { //检查其它订单
					if (!$cur_order) { //订单不存在
						array_push($error_sns, $val);
					} else {
					    if ($main_order['user_id'] != $cur_order['user_id']) { //订单用户是否相同
					        array_push($error_sns, $val);
					    } elseif ($main_order['consignee'] != $cur_order['consignee']) { //订单收货人是否相同
					        array_push($error_sns, $val);
					    } elseif ($main_order['process_status'] != $cur_order['process_status']) { //订单处理状态是否相同
					    	array_push($error_sns, $val);
					    } elseif ($main_order['lock_status'] != $cur_order['lock_status']) { //订单锁定状态是否相同
					    	array_push($error_sns, $val);
					    } elseif ($GLOBALS['_CFG']['use_ors'] && ($main_order['range_status'] != $cur_order['range_status'])) { //配货状态
					    	array_push($error_sns, $val);
					    } elseif ($main_order['extension_code'] != '' || $cur_order['extension_code'] != 0) { //是否普通订单
					    	array_push($error_sns, $val);
					    } elseif (($cur_order['order_status'] != OS_UNCONFIRMED && $cur_order['order_status'] != OS_CONFIRMED)
					    	|| ($cur_order['pay_status'] != PS_UNPAYED && $cur_order['pay_status'] != PS_PAYED)
					    	|| ($cur_order['shipping_status'] != SS_UNSHIPPED)) { //检查从订单状态、支付状态、发货状态
					    	array_push($error_sns, $val);
					    } elseif (($main_order['order_status'] != $cur_order['order_status']) 
					    	|| ($main_order['pay_status'] != $cur_order['pay_status']) 
					    	|| ($main_order['shipping_status'] != $cur_order['shipping_status'])) { //检查主从订单、支付、发货状态是否相同
					    	array_push($error_sns, $val);
					    } else {
		    				array_push($success_sns, $val);
					    }
					}
				}
			}
		}
		
		if ($accept) { //主订单符合要求
			if (count($success_sns) <= 0) {
				foreach($error_sns as $key => $val) {
					$note .= '<br/><font color="red">订单 ' . $val . ' 不能合并，请检查订单的各种状态。</font>';
				}
				//$note .= '<br/><br/>订单 ' . implode(',', $error_sns) . ' 不能合并，请检查订单的各种状态。';
				$accept = 0;
			} elseif (count($success_sns) == count($order_sns)) {
				foreach($success_sns as $key => $val) {
					$note .= '<br/><font color="green">订单 ' . $val . ' 可以合并。</font>';
				}
				//$note .= '<br/><br/>订单 ' . implode(',', $success_sns) . ' 可以合并。';
			} else {
				foreach($success_sns as $key => $val) {
					$note .= '<br/><font color="green">订单 ' . $val . ' 可以合并。</font>';
				}
				foreach($error_sns as $key => $val) {
					$note .= '<br/><font color="red">订单 ' . $val . ' 不能合并，请检查订单的各种状态。</font>';
				}
				//$note .= '<br/><br/>订单 ' . implode(',', $success_sns) . ' 可以合并。<br/><br/>订单 ' . implode(',', $error_sns) . ' 不能合并，请检查订单的各种状态。';
			}
		}
		
		$smarty->assign('ur_here', '订单合并检查');
		$smarty->assign('note', $note);
		$smarty->assign('accept', $accept);
		$smarty->assign('order_id', $_REQUEST['order_id']);
		$smarty->assign('operation', 'merge_orders');
		$smarty->assign('batch', 1);
		
		$smarty->display('order_note.tpl');
		exit;
	}
	
	/* 多订单合并处理 */
	elseif ('merge_orders' == $operation) {
		$order_sns = $order_id_list;
		$result = merge_orders($order_sns);
		if (!empty($result['message'])) {
			$link[0]['text'] = '订单合并';
    		$link[0]['href'] = 'order.php?act=order_merge';
    		$link[1]['text'] = '订单列表';
    		$link[1]['href'] = 'order.php?act=list';
    		sys_msg($result['message'], 0, $link);
		}
		exit;
	}
	
	/* 默认 */
	else
	{
		die('invalid params');
	}

	/* 取得备注信息 */
	// $action_note = $_REQUEST['action_note'];

	if(empty($sn_not_list)) {
		$sn_list = empty($sn_list) ? '' : '更新的订单：' . join($sn_list, ',');
		$msg = $sn_list;
		$links[] = array('text' => '返回订单列表', 'href' => 'order.php?act=list&' . list_link_postfix());
		sys_msg($msg, 0, $links);
	} else {
		$order_list_no_fail = array();
		$sql = "SELECT * FROM " . $os->table('order_info') .
		" WHERE order_sn " . db_create_in($sn_not_list);
		$res = $db->query($sql);
		while($row = $db->fetchRow($res)) {
			$order_list_no_fail[$row['order_id']]['order_id'] = $row['order_id'];
			$order_list_no_fail[$row['order_id']]['order_sn'] = $row['order_sn'];
			$order_list_no_fail[$row['order_id']]['order_status'] = $row['order_status'];
			$order_list_no_fail[$row['order_id']]['shipping_status'] = $row['shipping_status'];
			$order_list_no_fail[$row['order_id']]['pay_status'] = $row['pay_status'];

			$order_list_fail = '';
			foreach(operable_list($row,$action_code) as $key => $value) {
				if($key != $operation) {
					$order_list_fail .= $_LANG['op_' . $key] . ',';
				}
			}
			$order_list_no_fail[$row['order_id']]['operable'] = $order_list_fail;
		}

		/* 模板赋值 */
		$smarty->assign('order_info', $sn_str);
		$smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => '订单列表'));
		$smarty->assign('order_list',   $order_list_no_fail);

		/* 显示模板 */
		assign_query_info();
		$smarty->display('order_operate_info.tpl');
	}
}

/*------------------------------------------------------ */
//-- 操作订单状态（处理提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'operate_post')
{
	/* 取得参数 */
	$order_id   = $_REQUEST['order_id'];        // 订单id
	$operation  = $_REQUEST['operation'];       // 订单操作

	/* 查询订单信息 */
	$order = order_info($order_id);

	/* 检查能否操作 */
	$operable_list = operable_list($order,$action_code);

	/* 取得备注信息 */
	$action_note = $_REQUEST['action_note'];

	/* 初始化提示信息 */
	$msg = '';

	/* 确认 */
	if ('confirm' == $operation)
	{
		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'confirm', true);
		
		//$log_already = order_action_judge($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
		$log_already = order_action_judge($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note);
		if($log_already){
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		}else{
			/* 标记订单为已确认 */
			update_order($order_id, array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
			update_order_amount($order_id);
			update_order_lock_status($order_id);
			/* 记录log */
			order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note);
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
		
		/* 发送邮件 */
		$cfg = $_CFG['send_confirm_email'];
		
		if ($cfg == '1') {
			$tpl = get_mail_template('order_confirm');
			$smarty->assign('order', $order);
			$smarty->assign('shop_name', $_CFG['shop_name']);
			$smarty->assign('send_date', local_date($_CFG['date_format']));
			$smarty->assign('sent_date', local_date($_CFG['date_format']));
			$content = $smarty->fetch('str:' . $tpl['template_content']);
			if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
				$msg = '发送邮件失败';
			}
		}
	}

	/* 未确认 */
	elseif ('unconfirm' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_UNCONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			update_order($order_id, array('order_status' => OS_UNCONFIRMED, 'range_status' => ORS_UNCONFIRMED));
			//update_order_amount($order_id);
			order_action($order['order_sn'], OS_UNCONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], ORS_UNCONFIRMED);
			/* 库存处理 */
			manage_good_inventory($order['order_id'], 'unconfirm');
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
	}

	/* 锁定 */
	elseif ('lock' == $operation)
	{
		$admin_id = $_SESSION['admin_id'];
		$lock_status = get_order_lock_status($order_id);

		if ($lock_status == 0) {
			update_order_lock_status($order_id,$admin_id);
		} else {
			sys_msg('你准备锁定的订单已被其他管理员锁定,请选择其他未被锁定的订单处理',1,array(),false);
		}

		/* 记录log */
		order_action($order['order_sn'], OS_LOCK, $order['shipping_status'], $order['pay_status'], $action_note);
	}

	/* 解锁 */
	elseif ('unlock' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_UNLOCK, $order['shipping_status'], $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			$admin_id = $_SESSION['admin_id'];
			update_order_lock_status($order_id, 0);
			/* 记录log */
			order_action($order['order_sn'], OS_UNLOCK, $order['shipping_status'], $order['pay_status'], $action_note);
		}
	}

	/* 付款 */
	elseif ('pay' == $operation)
	{
		$sql = 'select order_status from '.$os->table('order_info').' where order_id = '.$order_id;
		$order_status = $db->getOne($sql);
			
		$log_already = order_action_judge($order['order_sn'], $order_status, $order['shipping_status'], PS_PAYED, $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 库存处理 */
			manage_good_inventory($order['order_id'], 'pay', true);
		
			/* 标记订单为已确认、已付款，更新付款时间和已支付金额，如果是货到付款，同时修改订单为“收货确认” */
			if ($order['order_status'] != OS_CONFIRMED) {
				$arr['confirm_time']    = gmtime();
			}
			$arr['pay_status']  = PS_PAYED;
			$arr['pay_time']    = gmtime();
			$arr['money_paid']  = $order['money_paid'] + $order['order_amount'];
			$arr['order_amount']= 0;
			$payment = payment_info($order['pay_id']);
			/*
			if ($payment['is_cod'])
			{
				$arr['shipping_status'] = SS_RECEIVED;
				$order['shipping_status'] = SS_RECEIVED;
			}
			*/
			update_order($order_id, $arr);
			/* 记录log */
			order_action($order['order_sn'], $order_status, $order['shipping_status'], $arr['pay_status'], $action_note);
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
	}
	
	/* 设为未付款 */
	elseif ('unpay' == $operation)
	{
		$sql = 'select order_status from '.$os->table('order_info').' where order_id = '.$order_id;
		$order_status = $db->getOne($sql);		
		
		$log_already = order_action_judge($order['order_sn'], $order_status, $order['shipping_status'], PS_UNPAYED, $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为未付款，更新付款时间和已付款金额 */
			$arr = array(
				'pay_status'    => PS_UNPAYED,
				'pay_time'      => 0,
				'money_paid'    => 0,
				'order_amount'  => $order['money_paid']
			);
			update_order($order_id, $arr);
			/* todo 处理退款 */
			$refund_type = @$_REQUEST['refund'];
			$refund_note = @$_REQUEST['refund_note'];
			order_refund($order, $refund_type, $refund_note);
			/* 记录log */
			order_action($order['order_sn'], $order_status, $order['shipping_status'], $arr['pay_status'], $action_note);
			/* 库存处理 */
			manage_good_inventory($order['order_id'], 'unpay');
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
	}

	/* 设为结算 */
	elseif ('pay_finish' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_FINISH, SS_SHIPPED, PS_PAYED_FINISH, $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			$sql = 'UPDATE ' . $os->table('order_info') . ' SET order_status = '.OS_FINISH.',shipping_status = '.SS_SHIPPED.',pay_status = '
				   .PS_PAYED_FINISH.' WHERE order_id = '.$order_id;
			$db->query($sql);
			/* 记录log */
			order_action($order['order_sn'], OS_FINISH, SS_SHIPPED, PS_PAYED_FINISH, $action_note);
		}
	}

	/* 拣货 */
	elseif ('prepare' == $operation)
	{
		/* 标记订单为已确认，拣货中 */
		if ($order['order_status'] != OS_CONFIRMED) {
			$arr['order_status']    = OS_CONFIRMED;
			$arr['confirm_time']    = gmtime();
		}
		$arr['shipping_status']     = SS_PREPARING;
		update_order($order_id, $arr);

		/* 记录log */
		order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], $order['pay_status'], $action_note);

		/* 清除缓存 */
		clear_cache_files();
	}
	
	/* 发货 */
	elseif ('ship' == $operation)
	{
		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'ship', true);
		manage_good_inventory($order['order_id'], 'confirm');
		
		/* 标记订单为已确认 “已发货” */
		/* 更新发货时间和发货单号 */
		$shipping_status = SS_SHIPPED;			
		$log_already = order_action_judge($order['order_sn'], $order['order_status'], $shipping_status, $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 取得发货单号 */
			$invoice_no = $_REQUEST['invoice_no'];

			/* 对虚拟商品的支持 */
			$virtual_goods = get_virtual_goods($order_id);
			if (!empty($virtual_goods)) {
				if (!virtual_goods_ship($virtual_goods, $msg, $order['order_sn'])) {
					$links[] = array('text' => '订单信息', 'href' => 'order.php?act=info&order_id=' . $order_id);
					sys_msg($msg, 0, $links);
				}
			}

			if ($order['order_status'] != OS_CONFIRMED) {
				$arr['order_status']    = OS_CONFIRMED;
				$arr['confirm_time']    = gmtime();
			}
			$arr['shipping_status']     = $shipping_status;
			$arr['shipping_time']       = gmtime();
			$arr['invoice_no']          = $invoice_no;
			update_order($order_id, $arr);
			$db->query('UPDATE ' . $os->table('order_goods') . ' SET send_number = goods_number WHERE order_id = '.$order_id);
			$order['invoice_no'] = $invoice_no;
			/* 记录log */
			order_action($order['order_sn'], $order['order_status'], $shipping_status, $order['pay_status'], $action_note);
			//调用taobao发货 
    		taobaoSendOrder($order['order_sn']) ; //调用taobao发货 成功返回0 失败返回0  by winner add 2009-10-24  
		}	
		
		/* 如果订单用户不为空，计算积分，并发给用户；发红包 */
		if ($order['user_id'] > 0) {
			/* 取得用户信息 */
			$user = user_info($order['user_id']);
			
			/* 计算并发放积分 */
			$integral = integral_to_give($order);

			log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf('订单 %s 赠送的积分', $order['order_sn']));

			/* 发放红包 */
			send_order_bonus($order_id);
		}

		/* 发送邮件 */
		$cfg = $_CFG['send_ship_email'];
		if ($cfg == '1') {
			$tpl = get_mail_template('deliver_notice');
			$smarty->assign('order', $order);
			$smarty->assign('send_time', local_date($_CFG['time_format']));
			$smarty->assign('shop_name', $_CFG['shop_name']);
			$smarty->assign('send_date', local_date($_CFG['date_format']));
			$smarty->assign('sent_date', local_date($_CFG['date_format']));
			$smarty->assign('confirm_url', $os->url() . 'receive.php?id=' . $order['order_id'] . '&con=' . rawurlencode($order['consignee']));
			$smarty->assign('send_msg_url',$os->url() . 'user.php?message_list&order_id=' . $order['order_id']);
			$content = $smarty->fetch('str:' . $tpl['template_content']);
			if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
				$msg = '发送邮件失败';
			}
		}

		/* 如果需要，发短信 */
		if ($GLOBALS['_CFG']['sms_order_shipped'] == '1' && $order['mobile'] != '') {
			include_once('../includes/cls_sms.php');
			$sms = new sms();
			$sms->send($order['mobile'], sprintf('您的订单%s已于%s发货 [%s]', $order['order_sn'],
			local_date('m月j日G时'), $GLOBALS['_CFG']['shop_name']), 0);
		}

		/* 清除缓存 */
		clear_cache_files();
	}
	
	/* 设为未发货 */
	elseif ('unship' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], $order['order_status'], SS_UNSHIPPED, $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为“未发货”，更新发货时间 */
			update_order($order_id, array('shipping_status' => SS_UNSHIPPED, 'shipping_time' => 0, 'invoice_no' => ''));
			/* 记录log */
			order_action($order['order_sn'], $order['order_status'], SS_UNSHIPPED, $order['pay_status'], $action_note);
		}			
		
		/* 如果订单用户不为空，计算积分，并退回 */
		if ($order['user_id'] > 0) {
			/* 取得用户信息 */
			$user = user_info($order['user_id']);

			/* 计算并退回积分 */
			$integral = integral_to_give($order);
			log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于退货或未发货操作，退回订单 %s 赠送的积分', $order['order_sn']));

			/* todo 计算并退回红包 */
			return_order_bonus($order_id);
		}

		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'unship');

		/* 清除缓存 */
		clear_cache_files();
	}
	
	/* 追单 */
	elseif ('chase' == $operation)
	{
		$chased_or_not = intval($_REQUEST['chased_or_not']);
		
		/* 更新追单字段 */
		update_order($order_id, array('chased_or_not' => $chased_or_not));
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note);
		
		/* 清除缓存 */
		clear_cache_files();
	}
	
	/* 收货确认 */
	elseif ('receive' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], $order['order_status'], SS_RECEIVED, $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为“收货确认”，如果是货到付款，同时修改订单为已付款 */
			$arr = array('shipping_status' => SS_RECEIVED);
			$payment = payment_info($order['pay_id']);
			if ($payment['is_cod']) {
				$arr['pay_status'] = PS_PAYED;
				$order['pay_status'] = PS_PAYED;
			}
			update_order($order_id, $arr);
			/* 记录log */
			order_action($order['order_sn'], $order['order_status'], SS_RECEIVED, $arr['pay_status'], $action_note);
		}
	}
	
	/* 挂起订单 */
	elseif ('suspend' == $operation)
	{
		$arr = array();
		$arr['action_note'] = $action_note;
		$arr['suspend_note'] = isset($_REQUEST['suspend_note']) ? trim($_REQUEST['suspend_note']) : '';
		$arr['suspend_end_date'] = isset($_REQUEST['suspend_end_date']) ? local_strtotime($_REQUEST['suspend_end_date']) : '';
		
		$result = suspend_order($order['order_sn'], '', $arr);
	}
	
	/* 解挂订单 */
	elseif ('remove_suspend' == $operation)
	{
		$result = remove_suspend_order($order['order_sn'], '', $action_note);
	}
	
	/* 取消 */
	elseif ('cancel' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_CANCELED, $order['shipping_status'], $order['pay_status'], $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为“取消”，记录取消原因 */
			$cancel_note = isset($_REQUEST['cancel_note']) ? trim($_REQUEST['cancel_note']) : '';
			$arr = array(
				'order_status'  => OS_CANCELED,
				'to_buyer'      => $cancel_note,
				'pay_status'    => PS_UNPAYED,
				'pay_time'      => 0,
				'money_paid'    => 0,
				'order_amount'  => $order['money_paid']
			);
			update_order($order_id, $arr);

			/* todo 处理退款 */
			if ($order['money_paid'] > 0) {
				$refund_type = $_REQUEST['refund'];
				$refund_note = $_REQUEST['refund_note'];
				order_refund($order, $refund_type, $refund_note);
			}
			/* 记录log */
			order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], $order['pay_status'], $action_note);
			
			/* 库存处理 */
			manage_good_inventory($order['order_id'], 'cancel');
		}		
		
		/* 退还用户余额、积分、红包 */
		return_user_surplus_integral_bonus($order);

		/* 发送邮件 */
		$cfg = $_CFG['send_cancel_email'];
		if ($cfg == '1') {
			$tpl = get_mail_template('order_cancel');
			$smarty->assign('order', $order);
			$smarty->assign('shop_name', $_CFG['shop_name']);
			$smarty->assign('send_date', local_date($_CFG['date_format']));
			$smarty->assign('sent_date', local_date($_CFG['date_format']));
			$content = $smarty->fetch('str:' . $tpl['template_content']);
			if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
				$msg = '发送邮件失败';
			}
		}
	}
	
	/* 设为无效 */
	elseif ('invalid' == $operation)
	{
		$result = invalid_order($order['order_sn']);
	}
	
	/* 退货 */
	elseif ('return' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_RETURNED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为“退货”、“未付款”、“未发货” */
			$arr = array('order_status'     => OS_RETURNED,
				'pay_status'       => PS_UNPAYED,
				'shipping_status'  => SS_UNSHIPPED,
				'money_paid'       => 0,
				'order_amount'     => $order['money_paid']);
			update_order($order_id, $arr);

			/* todo 处理退款 */
			if ($order['pay_status'] != PS_UNPAYED) {
				$refund_type = $_REQUEST['refund'];
				$refund_note = $_REQUEST['refund_note'];
				order_refund($order, $refund_type, $refund_note);
			}
			/* 记录log */
			order_action($order['order_sn'], OS_RETURNED,$order['shipping_status'], $order['pay_status'], $action_note);
		}

		/* 如果订单用户不为空，计算积分，并退回 */
		if ($order['user_id'] > 0) {
			/* 取得用户信息 */
			$user = user_info($order['user_id']);

			/* 计算并退回积分 */
			$integral = integral_to_give($order);
			log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于退货或未发货操作，退回订单 %s 赠送的积分', $order['order_sn']));

			/* todo 计算并退回红包 */
			return_order_bonus($order_id);
		}

		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'return');

		/* 退货用户余额、积分、红包 */
		return_user_surplus_integral_bonus($order);

		/* 清除缓存 */
		clear_cache_files();
	}
	
	/* 售后 */
	elseif ('after_service' == $operation)
	{
		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '[' . '售后' . '] ' . $action_note);
	}

	/* 部分拒收 */
	elseif ('part_reject' == $operation)
	{
		/* 标记订单为“无效”、“未付款” */
		update_order($order_id, array('order_status' => OS_PARTREJECTED));

		/* 记录log */
		order_action($order['order_sn'], OS_PARTREJECTED, $order['shipping_status'], PS_UNPAYED, $action_note);

		// TODO 这块需要仔细斟酌一下
		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'part_reject');
	}

	/* 全部拒收 */
	elseif ('all_reject' == $operation)
	{
		/* 标记订单为“无效”、“未付款” */
		update_order($order_id, array('order_status' => OS_ALLREJECTED));

		/* 记录log */
		order_action($order['order_sn'], OS_ALLREJECTED, $order['shipping_status'], PS_UNPAYED, $action_note);

		// TODO 这块需要仔细斟酌一下
		/* 库存处理 */
		manage_good_inventory($order['order_id'], 'all_reject');
	}

	/* 完成 */
	elseif ('finish' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], OS_FINISH, $order['shipping_status'], PS_PAYED, $action_note);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			/* 标记订单为“无效”、“未付款” */
			update_order($order_id, array('order_status' => OS_FINISH));
			/* 记录log */
			order_action($order['order_sn'], OS_FINISH, $order['shipping_status'], $order['pay_status'], $action_note);
		}
	}

	/* 在仓库 */
	elseif ('inwarehouse' == $operation)
	{
		/* 标记订单为 ‘在仓库’ */
		update_order($order_id, array('shipping_status' => SS_INWAREHOUSE, 'shipping_time' => 0));

		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], SS_INWAREHOUSE, $order['pay_status'], $action_note);
	}

	/* 在司机 */
	elseif ('todriver' == $operation)
	{
		/* 标记订单为“在司机”*/
		update_order($order_id, array('shipping_status' => SS_TODRIVER, 'shipping_time' => 0));

		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], SS_TODRIVER, $order['pay_status'], $action_note);
	}

	/* 在配送站 */
	elseif ('atstation' == $operation)
	{
		/* 标记订单为“在配送站”*/
		update_order($order_id, array('shipping_status' => SS_ATSTATION, 'shipping_time' => 0));

		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], SS_ATSTATION, $order['pay_status'], $action_note);
	}

	/* 在配送员 */
	elseif ('todeliver' == $operation)
	{
		/* 标记订单为“在配送员”*/
		update_order($order_id, array('shipping_status' => SS_TODELIVER, 'shipping_time' => 0));

		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], SS_TODELIVER, $order['pay_status'], $action_note);
	}

	/* 站长确认 */
	elseif ('adminconfirm' == $operation)
	{
		/* 标记订单为“站长确认”*/
		update_order($order_id, array('shipping_status' => SS_ADMINCONFIRM, 'shipping_time' => 0));

		/* 记录log */
		order_action($order['order_sn'], $order['order_status'], SS_ADMINCONFIRM, $order['pay_status'], $action_note);
	}

	/* 配货中间界面 */
	elseif ('unbatch_range' == $operation) {
		$cur_order = order_info($order_id);
		$accept = 1;
		if (!$cur_order) {
			$note = '您选择的订单不存在，请核对。';	
			$accept = 0;	
		} else {
			$result = check_goods_inventory($cur_order['order_id'], 0);
			if ($result['code'] == 0) {
				$note .= '<br/><br/>订单 ' . $cur_order['order_sn'] . ' 可以配货。';
			} else {
				$note .= '<br/><br/>订单 ' . $cur_order['order_sn'] . ' 不能配货，请检查订单商品的当前可用库存。';
				$accept = 0;
			}
		}
		
		$smarty->assign('ur_here', '订单配货检查');
		$smarty->assign('note', $note);
		$smarty->assign('accept', $accept);
		$smarty->assign('order_id', $order_id);
		$smarty->assign('operation', 'range');
		$smarty->assign('batch', 0);
		
		$smarty->display('order_note.tpl');
		exit;
	}
	
	/* 配货 */
	elseif ('range' == $operation)
	{
		$result = range_order($order_id);
		if (!empty($result['message'])) {
			sys_msg($result['message']);
			exit;
		}
	}

	/* 返回待配货 */
	elseif ('unrange' == $operation)
	{
		$log_already = order_action_judge($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $order['range_status']);
		if ($log_already) {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		} else {
			update_order($order_id, array('range_status' => ORS_UNCONFIRMED));
			//update_order_amount($order_id);
			/* 记录log */
			order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], $action_note, $_SESSION['admin_name'], ORS_UNCONFIRMED);

			/* 库存处理 */
			manage_good_inventory($order['order_id'], 'unrange');
			/* 清除配货未成功订单记录 */
			$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $order['order_id'] . "'");
			/* 更新计划发货时间 */
			auto_update_shipping_delivery($order['order_id']);
		}
	}
	
	/* 设为问题单 */
	elseif ('question' == $operation)
	{
		$action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
		$result = question_order($order['order_sn'], $_REQUEST['reason_id'], '', $action_note);
		if (is_array($result) && !empty($result['message'])) {
		    $link[0]['text'] = '返回订单明细';
		    $link[0]['href'] = 'order.php?act=info&order_id='.$order_id."\n";
			sys_msg($result['message'], 0, $link);
			exit;
		} else {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		}
	}
	
	/* 返回正常订单 */
	elseif ('remove_question' == $operation)
	{
		$result = remove_question_order($order['order_sn']);
		if (is_array($result) && !empty($result['message'])) {
			$link[0]['text'] = '返回订单明细';
		    $link[0]['href'] = 'order.php?act=info&order_sn=' . $order['order_sn'];
			sys_msg($result['message']);
			exit;
		} else {
			os_header("Location: order.php?act=info&order_id=".$order_id. "\n");
			exit;
		}
	}
	
	else
	{
		die('invalid params');
	}
	/* 操作成功 */
	$links[] = array('text' => '订单信息', 'href' => 'order.php?act=info&order_id=' . $order_id);
	sys_msg('操作成功' . $msg, 0, $links);
}

/*------------------------------------------------------ */
//-- 配货未成功订单批量处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'out_batch')
{
	$ids = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;
	if (!$ids) {
		sys_msg('您没有选择任何记录，请核对。');
	} else {
		switch(trim($_REQUEST['type'])) {
			case 'set_unrange':
				$GLOBALS['db']->query("UPDATE " . $GLOBALS['os']->table('order_info') . " SET range_status='" . ORS_UNCONFIRMED . "' WHERE order_sn IN ( SELECT relating_order_sn FROM " . $GLOBALS['os']->table('order_out') . " WHERE id IN ( $ids ) )");
				$GLOBALS['db']->query("DELETE FROM " . $GLOBALS['os']->table('order_out') . " WHERE id IN ( $ids )");
				sys_msg('配货未成功订单批量处理成功。');
				break;
			
			case 'default':
				break;
		}
	}
}

/*------------------------------------------------------ */
//-- 配货未成功订单列表（失败、缺货）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'out_list')
{
	/* 模板赋值 */
	$smarty->assign('ur_here', '配货未成功订单列表');
	$smarty->assign('full_page',        1);

	$arr = array();

	$arr['relating_order_sn']   = trim($_POST['relating_order_sn']);
	$arr['from_reason']  		= trim($_POST['from_reason']);
	$arr['process_mode']        = isset($_POST['process_mode']) ? intval($_POST['process_mode']) : -1;
	$arr['process_status']      = isset($_POST['process_status']) ? intval($_POST['process_status']) : -1;
	$arr['start_time'] 			= trim($_POST['start_time']);
	$arr['end_time']   			= trim($_POST['end_time']);
	
	$smarty->assign("queryPara", $arr);
	
	$order_out_list = order_out_list($arr);
	
	$smarty->assign('order_out_list',   $order_out_list['order_out_list']);
	$smarty->assign('filter',       $order_out_list['filter']);
	$smarty->assign('record_count', $order_out_list['record_count']);
	$smarty->assign('page_count',   $order_out_list['page_count']);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_out_list.tpl');
}

/*------------------------------------------------------ */
//-- 配货未成功订单处理页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_out_process')
{
	/* 模板赋值 */
	$smarty->assign('ur_here', '配货未成功订单处理');
	$smarty->assign('action_link', array('href' => 'order.php?act=out_list', 'text' => '配货未成功订单列表'));
	$smarty->assign('full_page',        1);

	$order_out_id = intval($_GET['id']);
	if ($_GET['order_id']) { $order_out_id = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('order_out') . " WHERE relating_order_id='" . $_GET['order_id'] . "'"); }
	if (!$order_out_id) {
		sys_msg('此订单不是配货未成功订单，请核对。');
	}
	
	$sql = 'SELECT * FROM ' . $os->table('order_out') . ' WHERE id = ' . $order_out_id;
	$order_out = $db->getRow($sql);
	
	$order_out['relating_order_id'] = $GLOBALS['db']->getOne("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE order_sn='" . $order_out['relating_order_sn'] . "'");
	$order_out['add_time']   = local_date('Y-m-d H:i', $order_out['add_time']);
	$order_out['start_time'] = local_date('Y-m-d H:i', $order_out['start_time']);
	$order_out['end_time']   = local_date('Y-m-d H:i', $order_out['end_time']);
	$order_id = $GLOBALS['db']->getOne("SELECT oi.order_id FROM " . $GLOBALS['os']->table('order_info') . " AS oi, " . $GLOBALS['os']->table('order_out') . " AS oo WHERE oi.order_sn=oo.relating_order_sn AND oo.id='{$order_out_id}'");
	$result = check_goods_inventory($order_id);
	if ($result['code'] == 0) { $order_out['available'] = '1'; }
	else { $order_out['available'] = '0'; }	
	
	$smarty->assign('order_out',   $order_out);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_out_process.tpl');
}

/*------------------------------------------------------ */
//-- 待配货订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'torange_list')
{
	/* 更新订单承诺发货天数 */
	if ($_CFG['use_promise_delivery']) { auto_update_shipping_days(); }
	
	/* 自动配货 */
	if ($_CFG['use_ors']) { auto_range(); }
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '待配货订单列表');

	$status_list[OS_UNCONFIRMED] = '待确认';
	$smarty->assign('status_list', $status_list);   // 订单状态

	$smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
	$smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
	$smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
	$smarty->assign('full_page',        1);
	
	if($action_name_list == 'all') {
		$smarty->assign('invoice_print',1);
	} elseif(in_array('order_invoice_print',$action_code)) {
		$smarty->assign('invoice_print',1);
	}
	$type = 'torange_list';
	$order_list = order_list($type);
	
	$smarty->assign('order_list',   $order_list['orders']);
	$smarty->assign('filter',       $order_list['filter']);
	$smarty->assign('record_count', $order_list['record_count']);
	$smarty->assign('page_count',   $order_list['page_count']);
	$smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');
	
	/* 载入配送方式 */
	$smarty->assign('shipping_list', shipping_list());
	
	// 增加对配送站搜索的功能
	$sql = 'select s.id,s.station_name from '.$os->table('delivery_station').' as s order by s.id asc';
	$station_list = $db->getAll($sql);
	$smarty->assign('station_list', $station_list);
	
	// 结束添加
	if(in_array('order_invoice_print', $action_code)){
		$smarty->assign('b_invoice_print',  1);
	}
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_torange_list.tpl');
}

/*------------------------------------------------------ */
//-- 缺货商品统计
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'out_statistic')
{
	/* 获得缺货商品 */
	$out_statistic = out_statistic();
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '缺货商品统计');
	$smarty->assign('full_page', 1);
	$smarty->assign('out_goods', 	$out_statistic['out']);
	$smarty->assign('filter',       $out_statistic['filter']);
	$smarty->assign('record_count', $out_statistic['record_count']);
	$smarty->assign('page_count',   $out_statistic['page_count']);
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_out_statistic.tpl');
}

/*------------------------------------------------------ */
//-- 缺货商品关联订单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'out_details')
{
	$arr = array();
	$goods_id = intval($_REQUEST['goods_id']);
	$color_id = intval($_REQUEST['color_id']);
	$size_id = intval($_REQUEST['size_id']);
	if ($goods_id <= 0 || $color_id <= 0 || $size_id <= 0) {
		sys_msg('商品关联ID信息不正确，请核对。');
		exit;
	} else {
		$arr['goods_id'] = $goods_id;
		$arr['color_id'] = $color_id;
		$arr['size_id'] = $size_id;
		/* 获得缺货商品关联订单 */
		$out_details = out_details($arr);
		
		/* 模板赋值 */
		$smarty->assign('ur_here', '缺货商品关联订单');
		$smarty->assign('full_page', 1);
		$smarty->assign('out_orders', 	$out_details['out']);
		$smarty->assign('filter',       $out_details['filter']);
		$smarty->assign('record_count', $out_details['record_count']);
		$smarty->assign('page_count',   $out_details['page_count']);
	
		/* 显示模板 */
		assign_query_info();
		$smarty->display('order_out_details.tpl');
	}
}

/*------------------------------------------------------ */
//-- 问题单订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'question_list')
{
	/* 模板赋值 */
	$smarty->assign('ur_here', '问题单订单列表');
	$smarty->assign('full_page',        1);

	$arr = array();
	$arr['relating_order_sn']   = trim($_POST['relating_order_sn']);
	$arr['question_reason']		= trim($_POST['question_reason']);
	
	$smarty->assign("queryPara", $arr);
	$order_question_list = order_question_list($arr);
	
	$smarty->assign('question_reasons', get_question_reason());
	$smarty->assign('order_question_list',   $order_question_list['order_question_list']);
	$smarty->assign('filter',       $order_question_list['filter']);
	$smarty->assign('record_count', $order_question_list['record_count']);
	$smarty->assign('page_count',   $order_question_list['page_count']);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_question_list.tpl');
}

/*------------------------------------------------------ */
//-- 单个设为问题单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'question_order')
{
	$order_sn = $_REQUEST['order_sn'];
	if(!empty($order_sn)) {
		$result = question_order($order_sn);
		
		/* 清除缓存 */
   		clear_cache_files();
   		/* 提示信息 */
   		$link[] = array('text' => '返回挂起单列表', 'href' => 'order.php?act=suspend_list' );
   		if ($result['code'] == 0) {
   			sys_msg('操作成功!', 0, $link);
   		} else {
   			sys_msg('操作失败!', 0, $link);
   		}
	} else {
		/* 提示信息 */
   		$link[] = array('text' => '返回挂起单列表', 'href' => 'order.php?act=suspend_list' );
   		sys_msg('对不起，该单据不能设为问题单!', 0, $link);
	}
	exit;
}

/*------------------------------------------------------ */
//-- 单个返回正常订单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_question')
{
	$order_sn = $_REQUEST['order_sn'];
	if(!empty($order_sn)) {
		$result = remove_question_order($order_sn);
		
		/* 清除缓存 */
   		clear_cache_files();
   		/* 提示信息 */
   		$link[0]['text'] = '返回订单明细';
		$link[0]['href'] = 'order.php?act=info&order_sn=' . $order_sn;
   		if ($result['code'] == 0) {
   			sys_msg('操作成功!', 0, $link);
   		} else {
   			sys_msg('操作失败!', 0, $link);
   		}
	} else {
		/* 提示信息 */
   		sys_msg('对不起，该单据不能返回正常订单!');
	}
	exit;
}

/*------------------------------------------------------ */
//-- 问题单订单处理页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_question_process')
{
	/* 模板赋值 */
	$smarty->assign('ur_here', '问题单订单处理');
	$smarty->assign('action_link', array('href' => 'order.php?act=question_list', 'text' => '问题单订单列表'));
	$smarty->assign('full_page',        1);

	$order_question_id = intval($_GET['id']);
	if ($_GET['order_id']) { $order_question_id = $GLOBALS['db']->getOne("SELECT id FROM " . $GLOBALS['os']->table('order_question') . " WHERE relating_order_id='" . $_GET['order_id'] . "'"); }
	if (!$order_question_id) {
		sys_msg('此订单不是问题单，请核对。');
	}
	
	$sql = 'SELECT * FROM ' . $os->table('order_question') . ' WHERE id = ' . $order_question_id;
	$order_question = $db->getRow($sql);
	
	$order_question['relating_order_id'] = $GLOBALS['db']->getOne("SELECT order_id FROM " . $GLOBALS['os']->table('order_info') . " WHERE order_sn='" . $order_question['relating_order_sn'] . "'");
	$order_question['add_time']   = local_date('Y-m-d H:i', $order_question['add_time']);
	$order_question['start_time'] = local_date('Y-m-d H:i', $order_question['start_time']);
	$order_question['end_time']   = local_date('Y-m-d H:i', $order_question['end_time']);
	$order_id = $GLOBALS['db']->getOne("SELECT oi.order_id FROM " . $GLOBALS['os']->table('order_info') . " AS oi, " . $GLOBALS['os']->table('order_question') . " AS oo WHERE oi.order_sn=oo.relating_order_sn AND oo.id='{$order_question_id}'");
	
	$smarty->assign('order_question',   $order_question);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_question_process.tpl');
}

/*------------------------------------------------------ */
//-- AJAX取商品信息
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'json')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON();

	$func = $_REQUEST['func'];
	if ($func == 'get_goods_info') {
		/* 取得商品信息 */
		$goods_id = $_REQUEST['goods_id'];
		$sql = "SELECT g.goods_id, c.cat_name, g.goods_sn, g.goods_name, b.brand_name, " .
			"g.goods_number, g.market_price, g.shop_price, g.promote_price, " .
			"g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_type, g.is_promote " .
			"FROM " . $os->table('goods') . " AS g " .
			"LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
			"LEFT JOIN " . $os->table('category') . " AS c ON g.cat_id = c.cat_id " .
			" WHERE g.goods_id = '$goods_id'";
		$goods = $db->getRow($sql);
		$today = gmtime();
		$goods['goods_price'] = ($goods['is_promote'] == 1 &&
		$goods['promote_start_date'] <= $today && $goods['promote_end_date'] >= $today) ?
		$goods['promote_price'] : $goods['shop_price'];

		/* 取得客户价格 */
		$sql = "SELECT p.user_price, r.rank_name " .
			"FROM " . $os->table('member_price') . " AS p, " .
			$os->table('user_rank') . " AS r " .
			"WHERE p.user_rank = r.rank_id " .
			"AND p.goods_id = '$goods_id' ";
		$goods['user_price'] = $db->getAll($sql);

		/* 取得商品属性 */
		$goods['spec_list']  = array();
		$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, c.*, gc.adjust_price FROM " . 
				$GLOBALS['os']->table('goods_color') . " gc LEFT JOIN ".$GLOBALS['os']->table('color') . " c ON ".
		        " gc.color_id = c.color_id LEFT JOIN " . $GLOBALS['os']->table('goods_inventory') . 
		        " gi ON gi.color_id = c.color_id LEFT JOIN " . $GLOBALS['os']->table('color_lib') .
		        " cl ON cl.img_id=gc.img_id WHERE gc.goods_id='$goods_id' and gi.goods_id ='$goods_id' 
		        group by c.color_id order by c.color_id desc";	
    	$gc_rows = $GLOBALS['db']->getAll($sql);
		    
		$first_color_id = 0;
    	if ($gc_rows && sizeof($gc_rows)>0) {		
    		$first_color_id = $gc_rows[0]['color_id'];
			$goods['spec_list']['color'] = $gc_rows;
    	}
    	
    	if ($first_color_id != 0) {
    		$sql = "SELECT s.*,gs.adjust_price FROM " . $GLOBALS['os']->table('goods_size') . " gs,".$GLOBALS['os']->table('size') . " s, ".$GLOBALS['os']->table('goods_inventory') . " gi ". "WHERE gs.goods_id='$goods_id' and gi.goods_id ='$goods_id' and gs.size_id=s.size_id and gi.color_id = ".$first_color_id." and gs.size_id = gi.size_id group by s.size_id order by s.size_id asc";
    		$gs_rows = $GLOBALS['db']->getAll($sql);
    		//$sql = "SELECT s.size_id,s.size_name,s.size_code,gs.adjust_price FROM ".$os->table('goods_size').
    		//" gs LEFT JOIN ".$os->table('size')." s ON gs.size_id=s.size_id  WHERE gs.goods_id='$goods_id'";
    		$goods['spec_list']['size'] = $gs_rows;
    	}
		echo $json->encode($goods);
	}
	
	if ($func == 'get_color_size')
	{	
		/* 取得商品信息 */
		$goods_id = intval($_REQUEST['goods_id']);
		$color_id = intval($_REQUEST['color_id']);
		
		$sql = 'select s.* from '.$os->table('goods_inventory').' gi LEFT JOIN '.$os->table('size').
			   ' s ON gi.size_id = s.size_id WHERE gi.goods_id = '.$goods_id.' AND gi.color_id = '.
			   $color_id.' order by s.size_id asc';
		$res['result'] = $db->getAll($sql);

		echo $json->encode($res);
	}
}

/*------------------------------------------------------ */
//-- 两订单AJAX合并（暂未使用）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'ajax_merge_order')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON();

	$main_order_sn  = empty($_POST['main_order_sn']) ? '' : json_str_iconv(substr($_POST['main_order_sn'], 1));
	$slave_order_sn = empty($_POST['slave_order_sn']) ? '' : json_str_iconv(substr($_POST['slave_order_sn'], 1));

	$m_result = merge_order($main_order_sn, $slave_order_sn);
	$result = array('error'=>0,  'content'=>'');
	if ($m_result === true) {
		$result['message'] = '操作成功';
	} else {
		$result['error'] = 1;
		$result['message'] = $m_result;
	}
	die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 删除订单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_order')
{
	$order_id = intval($_REQUEST['id']);

	/* 检查权限 */
	check_authz_json('order_remove');

	/* 检查订单是否允许删除操作 */
	$order = order_info($order_id);
	$operable_list = operable_list($order,$action_code);

	$GLOBALS['db']->query("DELETE FROM ".$GLOBALS['os']->table('order_info'). " WHERE order_id = '$order_id'");
	$GLOBALS['db']->query("DELETE FROM ".$GLOBALS['os']->table('order_goods'). " WHERE order_id = '$order_id'");
	$GLOBALS['db']->query("DELETE FROM ".$GLOBALS['os']->table('order_action'). " WHERE order_id = '$order_id'");

	if ($GLOBALS['db'] ->errno() == 0) {
		$url = 'order.php?act=query&' . str_replace('act=remove_order', '', $_SERVER['QUERY_STRING']);

		os_header("Location: $url\n");
		exit;
	} else {
		make_json_error($GLOBALS['db']->errorMsg());
	}
}

/*------------------------------------------------------ */
//-- 根据关键字和id搜索用户
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search_users')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON();

	$id_name = empty($_GET['id_name']) ? '' : json_str_iconv(trim($_GET['id_name']));

	$result = array('error'=>0, 'message'=>'', 'content'=>'');
	if ($id_name != '') {
		$sql = "SELECT user_id, user_name FROM " . $GLOBALS['os']->table('users') .
		" WHERE user_id LIKE '%" . mysql_like_quote($id_name) . "%'" .
		" OR user_name LIKE '%" . mysql_like_quote($id_name) . "%'" .
		" LIMIT 20";
		$res = $GLOBALS['db']->query($sql);

		$result['userlist'] = array();
		while ($row = $GLOBALS['db']->fetchRow($res)) {
			$result['userlist'][] = array('user_id' => $row['user_id'], 'user_name' => $row['user_name']);
		}
		
		if (count($result['userlist']) <= 0) {
			$result['error'] = 2;
		}
	} else {
		$result['error'] = 1;
		$result['message'] = 'NO KEYWORDS!';
	}

	die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 根据关键字搜索商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'search_goods')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON();

	$keyword = empty($_GET['keyword']) ? '' : json_str_iconv(trim($_GET['keyword']));

	$result = array('error'=>0, 'message'=>'', 'content'=>'');

	if ($keyword != '') {
		$sql = "SELECT goods_id, goods_name, goods_sn FROM " . $GLOBALS['os']->table('goods') .
		" WHERE is_delete = 0" .
		" AND is_on_sale = 1" .
		" AND is_alone_sale = 1" .
		" AND (goods_id LIKE '%" . mysql_like_quote($keyword) . "%'" .
		" OR goods_name LIKE '%" . mysql_like_quote($keyword) . "%'" .
		" OR goods_sn LIKE '%" . mysql_like_quote($keyword) . "%')" .
		" LIMIT 20";
		$res = $GLOBALS['db']->query($sql);

		$result['goodslist'] = array();
		while ($row = $GLOBALS['db']->fetchRow($res)) {
			$result['goodslist'][] = array('goods_id' => $row['goods_id'], 'name' => $row['goods_id'] . '  ' . $row['goods_name'] . '  ' . $row['goods_sn']);
		}
	} else {
		$result['error'] = 1;
		$result['message'] = 'NO KEYWORDS';
	}
	die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 编辑收货单号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_invoice_no')
{
	/* 检查权限 */
	check_authz_json('order_edit');

	$no = empty($_POST['val']) ? 'N/A' : json_str_iconv(trim($_POST['val']));
	$no = $no=='N/A' ? '' : $no;
	$order_id = empty($_POST['id']) ? 0 : intval($_POST['id']);

	if ($order_id == 0) {
		make_json_error('NO ORDER ID');
		exit;
	}

	$sql = 'UPDATE ' . $GLOBALS['os']->table('order_info') . " SET invoice_no='$no' WHERE order_id = '$order_id'";
	if ($GLOBALS['db']->query($sql)) {
		if (empty($no)) {
			make_json_result('N/A');
		} else {
			make_json_result(stripcslashes($no));
		}
	} else {
		make_json_error($GLOBALS['db']->errorMsg());
	}
}

/*------------------------------------------------------ */
//-- 编辑付款备注
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit_pay_note')
{
	/* 检查权限 */
	check_authz_json('order_edit');

	$no = empty($_POST['val']) ? 'N/A' : json_str_iconv(trim($_POST['val']));
	$no = $no=='N/A' ? '' : $no;
	$order_id = empty($_POST['id']) ? 0 : intval($_POST['id']);

	if ($order_id == 0) {
		make_json_error('NO ORDER ID');
		exit;
	}

	$sql = 'UPDATE ' . $GLOBALS['os']->table('order_info') . " SET pay_note='$no' WHERE order_id = '$order_id'";
	if ($GLOBALS['db']->query($sql)) {
		if (empty($no)) {
			make_json_result('N/A');
		} else {
			make_json_result(stripcslashes($no));
		}
	} else {
		make_json_error($GLOBALS['db']->errorMsg());
	}
}

/*------------------------------------------------------ */
//-- 获取订单商品信息
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'get_goods_info')
{
	/* 取得订单商品 */
	$order_id = isset($_REQUEST['order_id'])?intval($_REQUEST['order_id']):0;
	if (empty($order_id)) {
		make_json_response('', 1, '获取订单商品信息错误');
	}
	$goods_list = array();
	$goods_attr = array();

	$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, o.*, co.*,s.size_name,g.goods_thumb,
		g.goods_number AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
		" FROM " . $os->table('order_goods') . " AS o ".
		" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
		" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
		" LEFT join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id ".
		" left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id".
		 " left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
		" left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id ".
		" WHERE o.order_id = '{$order_id}' ";
    $res = $db->query($sql);
	while ($row = $db->fetchRow($res)) {
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0) {
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename)) {
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link'])) {
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}

		$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
		$row['formated_goods_price']    = price_format($row['goods_price']);
		$_goods_thumb = get_image_path($row['goods_id'], $row['goods_thumb'], true);
		//make_json_error($_goods_thumb);
		$_goods_thumb = $_CFG['pre_fetch_img'].$_goods_thumb.'?50,50';  //'.$_CFG['pre_fetch_img'].
		//(strpos($_goods_thumb, 'http://') === 0) ? $_goods_thumb : $os->url() . $_goods_thumb;
		$row['goods_thumb'] = $_goods_thumb;

		$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

		$img_item = '<a href="../'.$row['img_file'].'" target="_brank">
     <img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" w border="0" alt="'.$row['img_name'].'"/>
     </a>';
		//make_json_error($img_item);
		$row['img_item'] = $img_item;

		$goods_list[] = $row;
	}
	$attr = array();
	$arr  = array();
	foreach ($goods_attr AS $index => $array_val) {
		foreach ($array_val AS $value) {
			$arr = explode(':', $value);//以 : 号将属性拆开
			$attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
		}
	}

	$smarty->assign('goods_attr', $attr);
	$smarty->assign('goods_list', $goods_list);
	$str = $smarty->fetch('order_goods_info.tpl');
	$goods[] = array('order_id' => $order_id, 'str' => $str);
	make_json_result($goods);
}

/*------------------------------------------------------ */
//-- 获取退货单列表信息
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'returned_list')
{
	/* 取得退货单列表 */
	admin_priv('returned_list');

	/* 模板赋值 */
	$smarty->assign('ur_here', '退货（款）单列表');
	$smarty->assign('status_list', $_LANG['rs']);   // 退货单状态
	$smarty->assign('full_page',        1);

	$arr = array();
	
	$arr['return_sn']         = trim($_POST['return_sn']);
	$arr['return_consignee']  = trim($_POST['return_consignee']);
	$arr['status']            = intval($_POST['status']);

	$order_return_list = order_return_list('1',$arr);
	$smarty->assign('order_return_list',   $order_return_list['orders_return']);
	$smarty->assign('filter',       $order_return_list['filter']);
	$smarty->assign('record_count', $order_return_list['record_count']);
	$smarty->assign('page_count',   $order_return_list['page_count']);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_return_list.tpl');
}

/*------------------------------------------------------ */
//-- 移除退货单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_order_return')
{
	$order_return_id = intval($_REQUEST['id']);

	/* 检查权限 */
	admin_priv('return_remove');

	$GLOBALS['db']->query("DELETE FROM ".$GLOBALS['os']->table('order_return'). " WHERE id = '$order_return_id'");
	$GLOBALS['db']->query("DELETE FROM ".$GLOBALS['os']->table('order_return_goods'). " WHERE return_order_id = '$order_return_id'");

	if ($GLOBALS['db'] ->errno() == 0) {
		$url = 'order.php?act=return_query&' . str_replace('act=remove_order_return', '', $_SERVER['QUERY_STRING']);
		os_header("Location: $url\n");
		exit;
	}
}

/*------------------------------------------------------ */
//-- AJAX取退货单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'return_query')
{
	$order_return_list = order_return_list();

	$smarty->assign('order_return_list',   $order_return_list['orders_return']);
	$smarty->assign('filter',       $order_return_list['filter']);
	$smarty->assign('record_count', $order_return_list['record_count']);
	$smarty->assign('page_count',   $order_return_list['page_count']);

	/* 显示模板 */
	assign_query_info();

	make_json_result($smarty->fetch('order_return_list.tpl'), '', array('filter' => $order_return_list['filter'], 'page_count' => $order_return_list['page_count']));
}

/*------------------------------------------------------ */
//-- 打印日志列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'printlog_list')
{
	/* 检查权限 */
	admin_priv('printlog_list');

	$user_id   = !empty($_REQUEST['user_id'])       ? intval($_REQUEST['user_id']) : 0;
	$admin_ip  = !empty($_REQUEST['ip'])       ? $_REQUEST['ip']         : '';

	/* 查询IP地址列表 */
	$ip_list = array();
	$res = $db->query("SELECT DISTINCT ip_address FROM " .$os->table('order_printlog'));
	while ($row = $db->FetchRow($res)) {
		$ip_list[$row['ip_address']] = $row['ip_address'];
	}

	$users_list = array();
	$users_id_list = array();

	$sql = 'SELECT DISTINCT user_id FROM '.$os->table('order_printlog');
	$res = $db->getAll($sql);

	if ($res != '' && !empty($res)) {
		foreach ($res as $user_id) {
			array_push($users_id_list, $user_id['user_id']);
		}
		$user_ids = implode(',',$users_id_list);

		$sql = 'select user_id,user_name from '.$os->table('admin_user').' where user_id in ('.$user_ids.')';
		$users_list = $db->getAll($sql);
	}

	$smarty->assign('ur_here',   '订单打印日志');
	$smarty->assign('ip_list',   $ip_list);
	$smarty->assign('users_list',   $users_list);

	$smarty->assign('full_page', 1);

	$log_list = get_order_print_logs();

	$smarty->assign('log_list',        $log_list['list']);
	$smarty->assign('filter',          $log_list['filter']);
	$smarty->assign('record_count',    $log_list['record_count']);
	$smarty->assign('page_count',      $log_list['page_count']);

	$sort_flag  = sort_flag($log_list['filter']);
	//$smarty->assign($sort_flag['tag'], $sort_flag['img']);

	assign_query_info();
	$smarty->display("order_print_logs.tpl");
}

/*------------------------------------------------------ */
//-- 移除打印日志
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'drop_printlog')
{
	/* 检查权限 */
	admin_priv('drop_printlog');

	$count = 0;
	foreach ($_POST['checkboxes'] AS $key => $id) {
		$sql = "DELETE FROM " .$os->table('order_printlog'). " WHERE log_id = '$id'";
		$result = $db->query($sql);

		$count++;
	}
	if ($result) {
		admin_log('', 'remove', 'order_printlog');

		$link[] = array('text' => '返回打印日志列表', 'href' => 'order.php?act=printlog_list');
		sys_msg(sprintf('成功删除了 %d 个打印日志记录', $count), 0, $link);
	}
}

/*------------------------------------------------------ */
//-- 打印日志（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'printlog')
{
	/* 检查权限 */
	admin_priv('order_print');
	$order_sn = $_REQUEST['order_sn'];

	$print_logs = array();
	$sql = 'SELECT op.*, u.user_name FROM ' .$GLOBALS['os']->table('order_printlog'). ' AS op '.
		'LEFT JOIN ' .$GLOBALS['os']->table('admin_user'). ' AS u ON u.user_id = op.user_id WHERE log_info like "%'.$order_sn.'" order by log_id asc';
	$res = $db->getAll($sql);
	foreach ($res as $rows) {
		$rows['log_time'] = local_date($GLOBALS['_CFG']['time_format'], $rows['log_time']);
		$rows['print_type'] = $rows['print_type'] == 1?'订单':'配送单';
		$print_logs[] = $rows;
	}

	$smarty->assign('full_page',        0);
	$smarty->assign('log_list',$print_logs);
	$smarty->display('order_print_log.tpl');
}

/*------------------------------------------------------ */
//-- 获取可用红包
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'validate_bonus')
{
	$bonus_sn = trim($_REQUEST['bonus_sn']);
	$sql = 'select count(*) as count,t.type_money,t.use_start_date,t.use_end_date,b.bonus_id,b.used_time from '.$os->table('bonus_type').' as t,'.$os->table('user_bonus').' as b where t.type_id = b.bonus_type_id and t.send_type = '.SEND_BY_PRINT.' and b.bonus_sn = "'.$bonus_sn.'"';
	$res = $db->getRow($sql);
	
	$count = $res['count'];
	$used_time = $res['used_time'];
	$type_money = $res['type_money'];
	$use_start_date = $res['use_start_date'];
	$use_end_date = $res['use_end_date'];
	$bonus_id = $res['bonus_id'];	
	$now = gmtime();
	
	if ($count == 0) {
		make_json_result(BONUS_NOT_EXIST);
	} elseif ($count == 1) {
		if (($use_start_date > $now) || ($now > $use_end_date)) {
			make_json_result(BONUS_IS_EXPIRED);
		} else {
			if ($used_time > 0) {
				make_json_result(BONUS_IS_USED);
			} else {
				make_json_result(BONUS_AVALIABLE);
			}
		}
	}
}

/*------------------------------------------------------ */
//-- 获取退货单关联信息
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'order_returned')
{
	admin_priv('order_returned');

	$user = '';
	$order_id = $_REQUEST['order_id'];
	$order = order_info($order_id);
	$order['sub'] = $_REQUEST['sub'];
	
	/* 如果是货到付款，且未付款不允许退货（请填写拒收入库单） */
	if ($order['pay_name'] == '货到付款' && !$order['pay_status']) {
		sys_msg('货到付款且未付款，不允许退货，请填写拒收入库单。');
	}
	
	//$discount_rate = get_order_discount_rate_byid($order_id);
	
	/* 取得用户名 */
	if ($order['user_id'] > 0) {
		$user = user_info($order['user_id']);
		if (!empty($user)) {
			$order['user_name'] = $user['user_name'];
		}
	}

	$order['pay_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['pay_time']);
	$order['shipping_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['shipping_time']);
	$discount_sub = 0;

	/* 取得等待退货 与 已退货ID集合 */
	$return_order_ids = $db->getCol("SELECT id FROM " . $os->table('order_return') . " WHERE relating_order_sn='" . $order['order_sn'] . "' AND return_order_status<>'" . RS_INVALID . "'");
	if (is_array($return_order_ids)) {
		if(implode(',', $return_order_ids) != '') { $return_order_ids_str = " AND return_order_id IN (" . implode(',', $return_order_ids) . ")"; }
	}
	
	/* 取得订单商品 */
	$goods_list = array();
	$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, o.*, co.color_id,co.color_code,co.color_name,s.size_name,g.goods_number AS storage,
		o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
		" FROM " . $os->table('order_goods') . " AS o ".
		" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
		" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
		" LEFT join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id ".
		" left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id".
		" left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
		" left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id ".
		"WHERE o.order_id = '$order[order_id]' ";
		
	$res = $db->query($sql);
	while($row = $db->fetchRow($res)) {
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0) {
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename)) {
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link'])) {
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}
		
		if ($row['transaction_price'] > 0) {
			$row['discount_rate'] = $row['transaction_price'] / $row['goods_price'];
			$row['discount_price'] = $row['transaction_price'];
		} else {
			$row['discount_rate'] = 1;
			$row['discount_price'] = $row['goods_price'];
		}
		$row['formated_goods_price']      = price_format($row['goods_price']);			
		$row['formated_discount_price']   = price_format($row['discount_price']);
		$row['subtotal']         		  = $row['discount_price'] * $row['goods_number'];
		
		//等待退货 and 已退货
		if ($return_order_ids_str) {
			$row['valid_goods_number'] = $row['goods_number'] - $db->getOne("SELECT SUM(goods_return_number) AS goods_return_number FROM " . $os->table('order_return_goods') . " WHERE 1=1 $return_order_ids_str AND goods_id='" . $row['goods_id'] . "' AND color_id='" . $row['color_id'] . "' AND size_id='" . $row['size_id'] . "'");
			$row['valid_subtotal'] = $row['discount_price'] * $row['valid_goods_number'];
		} else {
			$row['valid_goods_number'] = $row['goods_number'];
			$row['valid_subtotal'] = $row['discount_price'] * $row['goods_number'];
		}
		
		//折扣虚礼不记入合计
		if ($row['is_gift'] > 0 && $GLOBALS['db']->getOne("SELECT act_type FROM " . $GLOBALS['os']->table('favourable_activity') . " WHERE act_id='" . $row['is_gift'] . "'") == 2) {
			;
		} else {
			$discount_sub += $row['valid_subtotal'];
		}
		
		$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

		if ($row['extension_code'] == 'package_buy') {
			$row['package_goods_list'] = get_package_goods($row['goods_id']);
		}

		$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" border="0" alt="'.$row['img_name'].'"/>';
		$row['img_item'] = $img_item;

		//折扣虚礼不记入退货
		if ($row['is_gift'] > 0 && $GLOBALS['db']->getOne("SELECT act_type FROM " . $GLOBALS['os']->table('favourable_activity') . " WHERE act_id='" . $row['is_gift'] . "'") == 2) {
			;
		} else {
			$goods_list[] = $row;
		}
	}

	/* 更新退款总金额 */
	if ($order['return_total_fee'] <= 0) { $order['return_total_fee'] = $discount_sub; }
	
	$smarty->assign('goods_list', $goods_list);

	$operable_return_list = operable_return_list($action_code);
	$smarty->assign('operable_return_list', $operable_return_list);

	$b_save = 1;
	$smarty->assign('b_save', $b_save);

	/* 模板赋值 */
	$smarty->assign('ur_here', '新增退货（款）单');
	$smarty->assign('action_link', array('href' => 'order.php?act=returned_list', 'text' => '退单列表'));
	$smarty->assign('full_page',        1);

	$order_return_pay = get_order_return_set(0);
	$order_return_reason  = get_order_return_set(1);

	$smarty->assign('order_return_reason', $order_return_reason);
	$smarty->assign('order_return_pay', $order_return_pay);
	$smarty->assign('discount_rate', $discount_rate);
	$smarty->assign('discount_sub', $discount_sub);
	
	$smarty->assign('user', $user);
	$smarty->assign('order', $order);
	
	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_return_info.tpl');
}

/*------------------------------------------------------ */
//-- 获取特定退货单信息
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'returned_order_info')
{
	admin_priv('return_view');

	$order_return_id = $_REQUEST['order_return_id'];

	$return_status = $_REQUEST['return_status'];

	$order_return = order_return_info($order_return_id);
	if($order_return_id != $order_return['id']) {
		$order_return_id = 0;
	}

	$order_return['return_reason']    =  get_order_return_info($order_return['return_reason']);
	$order_return['return_pay']       =  get_order_return_info($order_return['return_pay']);

	$discount_rate = get_order_discount_rate_bysn($order_return['relating_order_sn']);
	
	/* 取得退货单中的商品 */
	$goods_list = array();
	$sql = "SELECT  cl.img_file,cl.img_name,cl.img_code, o.*, co.*,s.size_name,g.goods_number AS storage,IFNULL(b.brand_name, '') AS brand_name " .
		" FROM " . $os->table('order_return_goods') . " AS o ".
		" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
		" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
		" LEFT join ".$GLOBALS['os']->table('color') ." as co on o.color_id = co.color_id ".
		" left join ".$GLOBALS['os']->table('goods_color') ." as gc on o.color_id = gc.color_id and o.goods_id = gc.goods_id".
		" left join ".$GLOBALS['os']->table('color_lib') ." as cl on gc.img_id = cl.img_id ".
		" left join ".$GLOBALS['os']->table('size') ." as s on o.size_id = s.size_id ".
		"WHERE o.return_order_id = '$order_return_id' ";
	$discount_sub = 0;
	$res = $db->query($sql);
	while ($row = $db->fetchRow($res)) {
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0) {
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename)) {
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link'])) {
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}

		$row['goods_number'] = $row['goods_buy_number'];

		//$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_return_number']);
		//$row['formated_goods_price']    = price_format($row['goods_price']);
		$row['formated_goods_price']      = price_format($row['goods_price']);
		$row['discount_price']    	  	  = round($row['goods_price'] * $discount_rate,2);
		$row['formated_discount_price']   = price_format(round($row['goods_price'] * $discount_rate,2));
		$row['subtotal']         		  = price_format($row['market_price']);

		$discount_sub += $row['market_price'];

		if ($row['extension_code'] == 'package_buy') {
			$row['package_goods_list'] = get_package_goods($row['goods_id']);
		}

		//$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40'" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>';
 		$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>';
		$row['img_item'] = $img_item;

		$goods_list[] = $row;
	}

	$smarty->assign('allow_update_return_goods', $GLOBALS['_CFG']['allow_update_return_goods']);
	$smarty->assign('order',         $order_return);
	$smarty->assign('goods_list',    $goods_list);	
	$smarty->assign('discount_sub',  price_format($discount_sub));
	$smarty->assign('return_status', $return_status);
	$smarty->assign('discount_rate', $discount_rate);
	
	/* 模板赋值 */
	$smarty->assign('ur_here', '退货单信息');
	$smarty->assign('full_page',        1);
	$smarty->assign('action_link', array('href' => 'order.php?act=returned_list', 'text' => '退货单列表'));

	/* 取得订单操作记录 */
	$act_log_list = array();
	$sql = "SELECT * FROM " . $os->table('order_return_action') . " WHERE order_return_id  = '$order_return_id' ORDER BY log_time DESC";
	$res = $db->query($sql);

	while ($row = $db->fetchRow($res)) {
		$row['return_order_status']    = $_LANG['rs'][$row['return_order_status']];
		$row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
		$act_log_list[] = $row;
	}
	$smarty->assign('act_log_list', $act_log_list);

	$operable_return_list = operable_return_list($action_code);
	$smarty->assign('operable_return_list', $operable_return_list);

	// 根据退货单状态,显示相应的按钮
	$b_save = 0;
	$b_confirm = 0;
	$b_unconfirm = 0;
	$b_pass = 0;
	$b_unpass = 0;
	$b_invalid = 1;
	$b_finish = 0;

	$return_order_status = $order_return['return_order_status'];

	if (RS_CONFIRMED == $return_order_status) {
		$b_unconfirm = 1;
		$b_pass = 1;
		$b_unpass = 1;
	}

	if (RS_UNCONFIRMED == $return_order_status) {
		$b_confirm = 1;
		$smarty->assign('flag',1);
	}

	if (RS_PASS == $return_order_status) {
		$b_unpass = 1;
		$b_finish = 1;
		$b_invalid = 0;
	}

	if (RS_UNPASS == $return_order_status) {
		$b_pass = 1;
		$b_finish = 1;
		$b_invalid = 1;
	}

	if (RS_FINISHED == $return_order_status || RS_INVALID == $return_order_status) {
		$b_invalid = 0;
	}

	$smarty->assign('b_save',$b_save);
	$smarty->assign('b_confirm',$b_confirm);
	$smarty->assign('b_unconfirm',$b_unconfirm);
	$smarty->assign('b_pass',$b_pass);
	$smarty->assign('b_unpass',$b_unpass);
	$smarty->assign('b_invalid',$b_invalid);
	$smarty->assign('b_finish',$b_finish);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_return_info.tpl');
}

/*------------------------------------------------------ */
//-- 更新退货单商品明细
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'update_return_goods')
{
	$result = array();
	$return_id = intval($_REQUEST['return_id']);
	$result = return_order($return_id, 'update_goods', $arr);
	if ($result['code'] == 0) {
		sys_msg('操作成功。');
	} else {
		sys_msg('操作失败。');
	}
	exit;
}

/*------------------------------------------------------ */
//-- 更新退货单总金额
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'update_return_fee')
{
	$id = $_REQUEST['return_id'];
	$fee = $_REQUEST['fee'];
	$result = array();
	$arr = array();
	$arr['return_total_fee'] = $fee;
	$result = return_order($id, 'update_fee', $arr);
	
	make_json_result($result);
	exit;
}

/*------------------------------------------------------ */
//-- 处理退货（款）单相关操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'return_operate')
{
	$user = '';
	$order_return_id = $_REQUEST['order_return_id'];
	$action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';

	if (isset($_POST['save']))
	{
		$require_note   = false;
		$action         = '保存';
		$operation      = 'save';
	}

	elseif (isset($_POST['confirm']))
	{
		$require_note   = false;
		$action         = '确认';
		$operation      = 'confirm';
	}

	elseif (isset($_POST['unconfirm']))
	{
		$require_note   = false;
		$action         = '未确认';
		$operation      = 'unconfirm';
	}

	elseif (isset($_POST['pass']))
	{
		$require_note   = false;
		$action         = '质检通过';
		$operation      = 'pass';
	}

	elseif (isset($_POST['unpass']))
	{
		$require_note   = false;
		$action         = '质检未通过';
		$operation      = 'unpass';
	}

	elseif (isset($_POST['invalid']))
	{
		$require_note   = false;
		$action         = '无效';
		$operation      = 'invalid';
	}

	elseif (isset($_POST['finish']))
	{
		$require_note   = false;
		$action         = '结算';
		$operation      = 'finish';
	}

	if ('save' == $operation) {
		$relating_order_sn 	= $_POST['relating_order_sn'];
		$order = order_info(0, $relating_order_sn);
		$result = array();
		$arr = array();
		$arr['relating_order_sn']     = $relating_order_sn;
		$arr['return_reason']		  = intval($_POST['return_reason']);
		$arr['return_pay'] 			  = intval($_POST['return_pay']);
		$arr['return_consignee'] 	  = $_POST['return_consignee'];
		$arr['return_email'] 		  = $_POST['return_email'];
		$arr['return_address'] 		  = $_POST['return_address'];
		$arr['return_zipcode'] 		  = $_POST['return_zipcode'];
		$arr['return_tel'] 			  = $_POST['return_tel'];
		$arr['return_mobile'] 		  = $_POST['return_mobile'];
		$arr['return_total_fee']	  = $_POST['return_total_fee'];
		$arr['action_note']			  = $action_note;
		$arr['action_user']  		  = $_SESSION['admin_name'];
		$arr['return_goods_amount']   = intval($_POST['return_goods_amount']);
		$arr['return_order_status']   = RS_UNCONFIRMED;
		$arr['return_goods_rec_id']   = $_POST['return_goods_rec_id'];
		$arr['return_goods_number']   = $_POST['return_goods_number'];
		$arr['return_discount_price'] = $_POST['return_discount_price'];
		$arr['has_goods_return']	  = $_POST['return_goods_rec_id'] ? 1 : 0;
		
		$result = return_order($order['order_id'], 'save', $arr);
		if ($result['code'] == 0 && $result['return_id']) {
			$links[] = array('text' => '退货（款）单信息', 'href' => 'order.php?act=returned_order_info&order_return_id=' . $result['return_id']);
			sys_msg('操作成功。', 0, $links);
		} else {
			sys_msg('操作失败。');
		}
		exit;
	} else {
		/* 直接处理还是跳到详细页面 */
		if ($require_note && $action_note == '') {
			/* 模板赋值 */
			$smarty->assign('require_note', $require_note); // 是否要求填写备注
			$smarty->assign('action_note', $action_note);   // 备注
			$smarty->assign('operation', $operation); 		// 操作

			/* 显示模板 */
			$smarty->assign('ur_here', '退货（款）单操作：' . $action);
			assign_query_info();
			$smarty->display('order_operate.tpl');
		} else {
			os_header("Location: order.php?act=return_operate_post&order_return_id=" . $order_return_id .
			"&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
			exit;
		}
	}
}

/*------------------------------------------------------ */
//-- 获取拒收入库单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'refused_list')
{
	admin_priv('refused_list');

	/* 模板赋值 */
	$smarty->assign('ur_here', '拒收入库单列表');

	$smarty->assign('status_list', $_LANG['rs']);   // 拒收入库单状态
	$smarty->assign('full_page',        1);

	$brr['refuse_sn']         = trim($_POST['refuse_sn']);
	$brr['refuse_consignee']  = trim($_POST['refuse_consignee']);
	$brr['status']            = intval($_POST['status']);
	
	$order_refuse_list = order_return_list(2,'',$brr);

	$smarty->assign('order_refuse_list',   $order_refuse_list['orders_return']);
	$smarty->assign('filter',       $order_refuse_list['filter']);
	$smarty->assign('record_count', $order_refuse_list['record_count']);
	$smarty->assign('page_count',   $order_refuse_list['page_count']);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_refuse_list.tpl');
}

/*------------------------------------------------------ */
//-- 获取特定拒收入库单信息
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'refused_order_info')
{
	admin_priv('refuse_view');
	
	$order_refuse_id = $_REQUEST['order_refuse_id'];

	$refuse_status = $_REQUEST['refuse_status'];

	$order_refuse = order_return_info($order_refuse_id, '', 2);
	if($order_refuse_id != $order_refuse['id']) {
		$order_refuse_id = 0;
	}

	/* 取得拒收入库单中的商品 */
	$goods_list = array();
	$sql = "SELECT  o.*, co.*,s.size_name,g.goods_number AS storage,IFNULL(b.brand_name, '') AS brand_name " .
	" FROM " . $os->table('order_return_goods') . " AS o ".
	" LEFT JOIN " . $os->table('goods') . " AS g ON o.goods_id = g.goods_id " .
	" LEFT JOIN " . $os->table('brand') . " AS b ON g.brand_id = b.brand_id " .
	" LEFT JOIN ".$GLOBALS['os']->table('color') ." AS co on o.color_id = co.color_id ".
	" LEFT JOIN ".$GLOBALS['os']->table('goods_color') ." AS gc on o.color_id = gc.color_id AND o.goods_id = gc.goods_id".
	" LEFT JOIN ".$GLOBALS['os']->table('color_lib') ." AS cl on gc.img_id = cl.img_id ".
	" LEFT JOIN ".$GLOBALS['os']->table('size') ." AS s on o.size_id = s.size_id ".
	"WHERE o.return_order_id = '$order_refuse_id' ";
	$res = $db->query($sql);
	while ($row = $db->fetchRow($res)) {
		/* 虚拟商品支持 */
		if ($row['is_real'] == 0) {
			/* 取得语言项 */
			$filename = SOURCE_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
			if (file_exists($filename)) {
				include_once($filename);
				if (!empty($_LANG[$row['extension_code'].'_link'])) {
					$row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
				}
			}
		}

		$row['goods_number'] = $row['goods_buy_number'];

		$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_return_number']);
		$row['formated_goods_price']    = price_format($row['goods_price']);

		if ($row['extension_code'] == 'package_buy') {
			$row['package_goods_list'] = get_package_goods($row['goods_id']);
		}

		//$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40'" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>';
 		$img_item = '<img src="'.$_CFG['pre_fetch_img'].$row['img_file'].'?40,40" width="40" height="40" border="0" alt="'.$row['img_name'].'"/>';
		$row['img_item'] = $img_item;

		$goods_list[] = $row;
	}

	$smarty->assign('goods_list', $goods_list);
	$smarty->assign('refuse_status', $refuse_status);
	$smarty->assign('order',        $order_refuse);

	/* 模板赋值 */
	$smarty->assign('ur_here', '拒收入库单信息');
	$smarty->assign('full_page',        1);
	$smarty->assign('action_link', array('href' => 'order.php?act=refused_list', 'text' => '拒收入库单列表'));

	/* 取得订单操作记录 */
	$act_log_list = array();
	$sql = "SELECT * FROM " . $os->table('order_return_action') . " WHERE order_return_id  = '$order_refuse_id' ORDER BY log_time DESC";
	$res = $db->query($sql);

	while ($row = $db->fetchRow($res)) {
		$row['return_order_status']    = $_LANG['rs'][$row['return_order_status']];
		$row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
		$act_log_list[] = $row;
	}
	$smarty->assign('act_log_list', $act_log_list);

	$operable_return_list = operable_return_list($action_code);
	$smarty->assign('operable_return_list', $operable_return_list);

	// 根据退货单状态,显示相应的按钮
	$b_save = 0;
	$b_confirm = 0;
	$b_unconfirm = 0;
	$b_pass = 0;
	$b_unpass = 0;
	$b_invalid = 1;
	$b_finish = 0;

	$refuse_order_status = $order_refuse['return_order_status'];

	if (RS_CONFIRMED == $refuse_order_status) {
		$b_unconfirm = 0;
		$b_pass = 1;
		$b_unpass = 1;
		$b_finish = 0;
	}

	if (RS_UNCONFIRMED == $refuse_order_status) {
		$b_confirm = 0;
		$smarty->assign('flag',1);
	}

	if (RS_PASS == $refuse_order_status) {
		$b_unpass = 1;
		$b_finish = 1;
		$b_invalid = 0;
	}

	if (RS_UNPASS == $refuse_order_status) {
		$b_pass = 1;
		$b_finish = 0;
	}

	if (RS_FINISHED == $refuse_order_status || RS_INVALID == $refuse_order_status) {
		$b_invalid = 0;
	}

	$smarty->assign('b_save',$b_save);
	$smarty->assign('b_confirm',$b_confirm);
	$smarty->assign('b_unconfirm',$b_unconfirm);
	$smarty->assign('b_pass',$b_pass);
	$smarty->assign('b_unpass',$b_unpass);
	$smarty->assign('b_invalid',$b_invalid);
	$smarty->assign('b_finish',$b_finish);

	/* 显示模板 */
	assign_query_info();
	$smarty->display('order_refuse_info.tpl');
}

/*------------------------------------------------------ */
//-- 处理拒收入库单相关操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'refuse_operate')
{
	$user = '';
	$admin_user = $_SESSION['admin_name'];
	$order_refuse_id = $_REQUEST['order_refuse_id'];
	$order = order_info($order_refuse_id);
	$action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';

	if (isset($_POST['pass']))
	{
		$require_note   = false;
		$action         = '质检通过';
		$operation      = 'pass';
	}
	elseif (isset($_POST['unpass']))
	{
		$require_note   = false;
		$action         = '质检未通过';
		$operation      = 'unpass';
	}
	elseif (isset($_POST['finish']))
	{
		$require_note   = false;
		$action         = '结算';
		$operation      = 'finish';
	}
	
	if ('pass' == $operation)
	{
		update_order_return($order_refuse_id, array('return_order_status' => RS_PASS,'return_order_ispass' => RS_PASS));
		$log_already = order_return_action_judge($order_refuse_id, RS_PASS, $action_note, $admin_user);
		if (!$log_already) {
			order_return_action($order_refuse_id, RS_PASS, $action_note, $admin_user);
		}
		os_header("Location: order.php?act=refused_order_info&order_refuse_id=".$order_refuse_id. "\n");
		exit;
	}
	elseif ('unpass' == $operation)
	{
		update_order_return($order_refuse_id, array('return_order_status' => RS_UNPASS,'return_order_ispass' => RS_UNPASS));
		$log_already = order_return_action_judge($order_refuse_id, RS_UNPASS, $action_note, $admin_user);
		if (!$log_already) {
			//记录log
			order_return_action($order_refuse_id, RS_UNPASS, $action_note, $admin_user);
		}
		os_header("Location: order.php?act=refused_order_info&order_refuse_id=".$order_refuse_id. "\n");
		exit;
	}
	elseif ('finish' == $operation)
	{
		update_order_return($order_refuse_id, array('return_order_status' => RS_FINISHED));
		$log_already = order_return_action_judge($order_refuse_id, RS_FINISHED, $action_note, $admin_user);
		if ($log_already) {
			os_header("Location: order.php?act=refused_order_info&order_refuse_id=".$order_refuse_id. "\n");
			exit;
		} else {
			/* 记录log */
			order_return_action($order_refuse_id, RS_FINISHED, $action_note, $admin_user);
		}

		$sql = 'select i.*,r.return_order_ispass from '.$GLOBALS['os']->table('order_info').' as i,'.$GLOBALS['os']->table('order_return')
		.' as r '.' where r.relating_order_sn = i.order_sn and id = '.$order_refuse_id;
		$order_refuse_tmp = $GLOBALS['db']->getAll($sql);
		$order_refuse = $order_refuse_tmp[0];
		$refuse_status = $order_refuse['return_order_ispass'];

		/* 标记订单为“退货”、“已结算”、“已发货” */
		$arr = array(
			'order_status'     => OS_RETURNED,
			'pay_status'       => PS_PAYED_FINISH,
			'shipping_status'  => SS_SHIPPED,
			'money_paid'       => 0,
			'order_amount'     => $order_refuse['money_paid']
		);
		update_order($order_refuse['order_id'], $arr);

		/* 记录log */
		order_action($order_refuse['order_sn'], OS_RETURNED, $order['shipping_status'], $order['pay_status'], '拒收入库');
		
		/* 如果订单用户不为空，计算积分，并退回 */
		if ($order_refuse['user_id'] > 0) {
			/* 取得用户信息 */
			$user = user_info($order_refuse['user_id']);

			/* 计算并退回积分 */
			$integral = integral_to_give($order_refuse);
			log_account_change($order_refuse['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于拒收入库操作，退回订单 %s 赠送的积分', $order_refuse['order_sn']));

			/* todo 计算并退回红包 */
			return_order_bonus($order_refuse['order_id']);
		}

		/* 如果使用库存，则增加库存（不论何时减库存都需要） */
		if ($_CFG['use_storage'] == '1') {
			// 修改以适应新的库存增减操作
			$sql = "SELECT o.goods_return_number,o.goods_id,o.color_id,o.size_id FROM " . $GLOBALS['os']->table('order_return_goods') .
			" as o WHERE o.return_order_id = '$order_refuse_id' AND is_real = 1";
			$res = $GLOBALS['db']->getAll($sql);
			foreach ($res as $res_goods) {
				$res_goods_id = $res_goods['goods_id'];
				$res_color_id = $res_goods['color_id'];
				$res_size_id  = $res_goods['size_id'];
				$goods_refuse_number = $res_goods['goods_return_number']; 
				$sql = "UPDATE " . $GLOBALS['os']->table('goods_inventory') .
				" SET goods_number_available = goods_number_available + ".$goods_refuse_number.",goods_number_actual = goods_number_actual + ".$goods_refuse_number.
				" WHERE goods_id = '" . $res_goods_id . "' and color_id = ".$res_color_id.' and size_id = '.$res_size_id; 
				$GLOBALS['db']->query($sql);
			}
		}

		/* 退货用户余额、积分、红包 */
		//return_user_surplus_integral_bonus($order_refuse);

		/* 清除缓存 */
		clear_cache_files();

		/* 显示模板 */
		assign_query_info();
		os_header("Location: order.php?act=refused_order_info&order_refuse_id=" . $order_refuse_id. "&refuse_status=".$refuse_status."\n");
		exit;
	}
}

/*------------------------------------------------------ */
//-- 导出TXT数据
/*------------------------------------------------------ */

elseif($_REQUEST['act'] == 'Export_order_list'){    
    require('export_order_list.php');    
	$order_list = Export_order_list();
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('nr',"\r\n");
    $html = ' 订单号  货物号  应收货款  收货人  收货人地址  电话  邮编  日期  公司  寄出地  寄达地  邮件单号';
    $html .= "\r\n";        
    $html .= $smarty->fetch('export_order_list.html');  
    $fname=empty($_REQUEST['end_time']) ? str_replace(":","",date("Y-m-d H:i")) :str_replace(":","",$_REQUEST['end_time']);	
    $countfile=ROOT_PATH."/sources/export/".$fname.".txt";
    if(!file_exists($countfile)) {
        fopen($countfile,"w"); //如果此文件不存在，则自动建立一个
    }
    $fp=fopen($countfile,"r");
    fclose($fp);
    $fp=fopen($countfile,"w");
    fwrite($fp,$html); //更新其值
    fclose($fp);
    downfile($countfile);			
}

/*------------------------------------------------------ */
//-- 退货单相关操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'return_operate_post')
{
	$result = array();
	$arr = array();
	$admin_user = $_SESSION['admin_name'];
	$action_note = $_REQUEST['action_note'];
	$operation = $_REQUEST['operation'];
	$order_return_id = $_REQUEST['order_return_id'];
	$return_status = $_REQUEST['return_status'];
	$arr['action_note'] = $action_note;
	$arr['admin_user'] = $admin_user;

	if ('confirm' == $operation) {
		$result = return_order($order_return_id, 'confirm', $arr);
	}

	if ('unconfirm' == $operation) {
		$result = return_order($order_return_id, 'unconfirm', $arr);
	}

	elseif ('pass' == $operation){
		$result = return_order($order_return_id, 'pass', $arr);
	}

	elseif ('unpass' == $operation){
		$result = return_order($order_return_id, 'unpass', $arr);
	}

	elseif ('invalid' == $operation){
		$result = return_order($order_return_id, 'invalid', $arr);
	}

	elseif ('finish' == $operation){
		$result = return_order($order_return_id, 'finish', $arr);
	}

	/* 显示模板 */
	assign_query_info();
	os_header("Location: order.php?act=returned_order_info&order_return_id=" . $order_return_id . "&return_status=" . $return_status . "\n");
	exit;
}

?>